code that has been used.
import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';
class LoadingScreen extends StatefulWidget {
#override
State<StatefulWidget> createState() {
return _LoadingScreenState();
}
}
class _LoadingScreenState extends State<LoadingScreen> {
#override
void initState() {
super.initState();
getLocation();
}
void getLocation() async {
try {
Position position = await Geolocator.getCurrentPosition(
desiredAccuracy: LocationAccuracy.low);
print(position);
} catch (e) {
print(e);
}
}
#override
Widget build(BuildContext context) {
return Scaffold();
}
}
Output:
Launching lib\main.dart on AOSP on IA Emulator in debug mode...
Running Gradle task 'assembleDebug'...
✓ Built build\app\outputs\flutter-apk\app-debug.apk.
Installing build\app\outputs\flutter-apk\app.apk...
Waiting for AOSP on IA Emulator to report its views...
Debug service listening on ws://127.0.0.1:51964/UEmjv7haU5w=/ws
Syncing files to device AOSP on IA Emulator...
I/Choreographer(14504): Skipped 116 frames! The application may be doing too much work on its main thread.
D/EGL_emulation(14504): eglMakeCurrent: 0xe8804b00: ver 3 1 (tinfo 0xea15ec70)
D/eglCodecCommon(14504): setVertexArrayObject: set vao to 0 (0) 1 2
I/OpenGLRenderer(14504): Davey! duration=2865ms; Flags=1, IntendedVsync=25791957327046, Vsync=25793890660302, OldestInputEvent=9223372036854775807, NewestInputEvent=0, HandleInputStart=25793896676340, AnimationStart=25793898368240, PerformTraversalsStart=25793934314440, DrawStart=25794433733640, SyncQueued=25794660799440, SyncStart=25794663501440, IssueDrawCommandsStart=25794663679640, SwapBuffers=25794747224740, FrameCompleted=25794825369240, DequeueBufferDuration=32086000, QueueBufferDuration=859000,
D/EGL_emulation(14504): eglMakeCurrent: 0xe88045c0: ver 3 1 (tinfo 0xea15e5e0)
D/eglCodecCommon(14504): setVertexArrayObject: set vao to 0 (0) 1 0
I/flutter (14504): The location service on the device is disabled.
Your output says "The location service on the device is disabled" so may you should check the permission in the manifest file. I suggest you to use the coarse and fine permissions together.
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
But you should make a previous verification of the location service too before do geolocation-requests.
you should chechk if the service is enabled:
bool isLocationServiceEnabled = await Geolocator.isLocationServiceEnabled();
print('location enabled: $isLocationServiceEnabled');
then check if the app has permissions:
LocationPermission permission = await Geolocator.checkPermission();
print(permission);
if you don't have permissions ask for them:
LocationPermission permission = await Geolocator.requestPermission();
print(permission);
with all that set up you can make a secure request
Position position = await Geolocator.getCurrentPosition(
desiredAccuracy: LocationAccuracy.low);
print(position);
You can use the codes :
var geolocator = Geolocator();
var locationOptions;
getPermission() async {
return Geolocator().checkGeolocationPermissionStatus();
}
then call this function in initState() :
getPermission().then((res) {
locationOptions =
LocationOptions(accuracy: LocationAccuracy.high, distanceFilter: 10);
});
geolocator.getPositionStream(locationOptions).listen((Position position) {
setState(() {
lat = position.latitude.toDouble();
long = position.longitude.toDouble();
});
});
Related
I am using MSAL with Android in B2C multiuser mode. The code I am following is from this example. It shows how to get a list of B2CUsers from a list of accounts:
private void loadAccounts() {
if (b2cApp == null) {
return;
}
b2cApp.getAccounts(new IPublicClientApplication.LoadAccountsCallback() {
#Override
public void onTaskCompleted(final List<IAccount> result) {
users = B2CUser.getB2CUsersFromAccountList(result);
updateUI(users);
}
#Override
public void onError(MsalException exception) {
displayError(exception);
}
});
}
But I also need to get the specific B2CUser after authenticating:
AcquireTokenParameters parameters = new AcquireTokenParameters.Builder()
.startAuthorizationFromActivity(getActivity())
.fromAuthority(B2CConfiguration.getAuthorityFromPolicyName(policyListSpinner.getSelectedItem().toString()))
.withScopes(B2CConfiguration.getScopes())
.withPrompt(Prompt.LOGIN)
.withCallback(getAuthInteractiveCallback())
.build();
b2cApp.acquireToken(parameters);
Which gives me a IAccount after from the authenticationResult:
#Override
public void onSuccess(IAuthenticationResult authenticationResult) {
/* Successfully got a token, use it to call a protected resource - MSGraph */
Log.d(TAG, "Successfully authenticated");
/* display result info */
displayResult(authenticationResult);
/* Reload account asynchronously to get the up-to-date list. */
loadAccounts();
}
But I can't seem to turn that into a B2CUser or get the ID from it as the:
iAuthenticationResult.getAccount().getId()
seems to return the policy appended to it and I cannot get the displayName either.
I have a Fresh application with basically no code added to it except the following Code.
If I try it in a simulator it goes into update state and says unsupported.
If I try to run in on a 6 generation ipad (with bluetooth turned on) the application crashes as soon as debugging exits UIButton231_TouchUpInside (and never goes into the catch).
Am I missing anything?
CBCentralManager _central;
partial void UIButton231_TouchUpInside(UIButton sender)
{
try
{
BluetoothLEManager();
}
catch (Exception e)
{
Console.Write(e);
}
}
protected void BluetoothLEManager()
{
try
{
_central = new CBCentralManager(DispatchQueue.CurrentQueue);
_central.DiscoveredPeripheral += (object sender, CBDiscoveredPeripheralEventArgs e) =>
{
Console.WriteLine("DiscoveredPeripheral: " + e.Peripheral.Name);
Console.WriteLine("RSSI: " + e.Peripheral.RSSI);
};
_central.UpdatedState += (object sender, EventArgs e) =>
{
Console.WriteLine("UpdatedState: " + _central.State);
};
_central.ConnectedPeripheral += (object sender, CBPeripheralEventArgs e) =>
{
Console.WriteLine("ConnectedPeripheral: " + e.Peripheral.Name);
};
_central.DisconnectedPeripheral += (object sender, CBPeripheralErrorEventArgs e) =>
{
Console.WriteLine("DisconnectedPeripheral: " + e.Peripheral.Name);
};
}
catch (Exception e)
{
Console.Write(e);
}
}
In the Image below (code is compacted to make the image shorter), debugging reaches line 62 just fine, but attempting to step over or to just let it continue will close the application, and breakpoints in the catch are not reached.
I have tried shared code in local site , and it also crashes and with some error logs :
After checking this line error :
Got a SIGABRT while executing native code. This usually indicates a fatal error in the mono runtime or one of the native libraries used by your application.
Sometimes that may be caused by permission in iOS . You can have a look at this aticle by James : New iOS 10 Privacy Permission Settings .
Starting in iOS 10, nearly all APIs that require requesting authorization and other APIs, such as opening the camera or photo gallery, require a new key value pair to describe their usage in the Info.plist.
However , in info.plist , you can add the permission of Bluetooth easily as follow and will forget another most important permission :
<key>NSBluetoothPeripheralUsageDescription</key>
<string>Add BlueTooth Peripheral Permission</string>
That's not enough for Bluetooth . You also need to add another permission :
<key>NSBluetoothAlwaysUsageDescription</key>
<string>use Bluetooth</string>
From native info.plist , you also will find it .
This permission is fundamental and necessary . Because this will pop up a permission Dialog window in iOS device .
By the way , there is an offical API about using Bluetooth in Xamarin iOS you can have a look .
public class MySimpleCBCentralManagerDelegate : CBCentralManagerDelegate
{
override public void UpdatedState (CBCentralManager mgr)
{
if (mgr.State == CBCentralManagerState.PoweredOn) {
//Passing in null scans for all peripherals. Peripherals can be targeted by using CBUIIDs
CBUUID[] cbuuids = null;
mgr.ScanForPeripherals (cbuuids); //Initiates async calls of DiscoveredPeripheral
//Timeout after 30 seconds
var timer = new Timer (30 * 1000);
timer.Elapsed += (sender, e) => mgr.StopScan();
} else {
//Invalid state -- Bluetooth powered down, unavailable, etc.
System.Console.WriteLine ("Bluetooth is not available");
}
}
public override void DiscoveredPeripheral (CBCentralManager central, CBPeripheral peripheral, NSDictionary advertisementData, NSNumber RSSI)
{
Console.WriteLine ("Discovered {0}, data {1}, RSSI {2}", peripheral.Name, advertisementData, RSSI);
}
}
public partial class HelloBluetoothCSharpViewController : UIViewController
{
MySimpleCBCentralManagerDelegate myDel;
public override void ViewDidLoad ()
{
base.ViewDidLoad ();
//Important to retain reference, else will be GC'ed
myDel = new MySimpleCBCentralManagerDelegate ();
var myMgr = new CBCentralManager (myDel, DispatchQueue.CurrentQueue);
}
We are developing normal bar code scanner app for windows surface tablets. In onNavigatedTo method of page we are invoking camera..
var devices = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture);
await App.camera.InitializeAsync(new MediaCaptureInitializationSettings
{
VideoDeviceId = devices[1].Id
});
cap.Source = App.camera;
cap.Visibility = Visibility.Visible;
await App.camera.StartPreviewAsync();
It is working fine.
Now App goes to background and comes back to foreground. But we are unable to invoke camera
again on resume using same code
await App.camera.StartPreviewAsync();
How to do it?
You need to use events such as Activated and VisibilityChanged :
private MediaCapture m_mediaCaptureMgr;
public MainPage()
{
this.InitializeComponent();
Window.Current.Activated+=Current_Activated;
Window.Current.VisibilityChanged+= Current_VisibilityChanged;
}
And then Initialize and StartPreview your camera on Current_Activated :
private async void Current_Activated(object sender, WindowActivatedEventArgs e)
{
try
{
m_mediaCaptureMgr = new Windows.Media.Capture.MediaCapture();
await m_mediaCaptureMgr.InitializeAsync();
cap.Source = m_mediaCaptureMgr;
await m_mediaCaptureMgr.StartPreviewAsync();
}
catch (Exception exception)
{
new MessageDialog("Unable to start the video capture.").ShowAsync();
}
}
And Stop Camera on Current_VisibilityChanged :
private async void Current_VisibilityChanged(object sender, VisibilityChangedEventArgs e)
{
try
{
await m_mediaCaptureMgr.StopPreviewAsync();
}
catch (Exception exception)
{
}
}
I'm trying to implement Game Center into my game but i have problems with it.
Here is my Main.cs code :
namespace iosgame
{
public class Application
{
[Register ("AppDelegate")]
public partial class AppDelegate : IOSApplication {
MainViewController mainViewController;
public AppDelegate(): base(new Game(new StaticsDatabase(),new StoreDatabase(),new InappPurchase(),new Social(),new MissionsDatabase()), getConfig()) {
}
internal static IOSApplicationConfiguration getConfig() {
IOSApplicationConfiguration config = new IOSApplicationConfiguration();
config.orientationLandscape = true;
config.orientationPortrait = false;
config.useAccelerometer = false;
config.useMonotouchOpenTK = true;
config.useObjectAL = true;
return config;
}
//
// This method is invoked when the application has loaded and is ready to run. In this
// method you should instantiate the window, load the UI into it and then make the window
// visible.
//
// You have 17 seconds to return from this method, or iOS will terminate your application.
//
public override bool FinishedLaunching (UIApplication app, NSDictionary options)
{
base.FinishedLaunching(app,options);
UIViewController controller = ((IOSApplication)Gdx.app).getUIViewController();
mainViewController = new MainViewController();
controller.View.Add(mainViewController.View);
return true;
}
private bool isGameCenterAPIAvailable()
{
return UIDevice.CurrentDevice.CheckSystemVersion (4, 1);
}
}
static void Main (string[] args)
{
UIApplication.Main (args, null, "AppDelegate");
}
}
}
And here is the superclass of that Main.cs : https://github.com/libgdx/libgdx/blob/master/backends/gdx-backend-iosmonotouch/src/com/badlogic/gdx/backends/ios/IOSApplication.java
I'm trying to use this https://github.com/xamarin/monotouch-samples/blob/master/GameCenterSample/GameCenterSample/MainViewController.cs example but i can't see any authenticate window in my game.I can see "Welcome back ,name" notification but after i log out from gamecenter app and reopen my game but i can't see any authentication window.
How can i fix it?
Thanks in advance
Just call this in FinishedLaunching:
if (!GKLocalPlayer.LocalPlayer.Authenticated) {
GKLocalPlayer.LocalPlayer.Authenticate (error => {
if (error != null)
Console.WriteLine("Error: " + error.LocalizedDescription);
});
}
This should display a Game Center "toast" saying "Welcome back, Player 1".
Here are some ideas if this doesn't work:
Make sure you have setup a new bundle id in the developer portal, and declare it in your Info.plist
Start filling out your app details in iTunes connect (Minimum is description, keywords, icon, 1 screenshot), and make sure to enable Game Center and add your new game to a group
Login with a test iTunes user in Game Center (create in ITC), or the login associated with your developer account
PS - I wouldn't worry about checking for iOS 4.1, just target iOS 5.0 and higher these days.
I'm trying to run a simple midlet on Java ME SDK 3.0 integrated into Netbeans 7.1 on Windows 7 Ultimate (just a UI). It was running fine until yesterday but now its showing an error and i can't see the midlet in the emulator. I don't think its anything related to compatibility issues because the applications were running just fine the other day. Could someone help me rectify this glitch or whatever it is? (No error in program i guess)
import java.io.IOException;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.MIDlet;
public class Facebook extends MIDlet {
public void startApp() {
Form f = new Form("Facebook Login");
try {
Image g = Image.createImage("/Facebook 2.png");
ImageItem img = new ImageItem(null, g, Item.LAYOUT_CENTER, null, Item.PLAIN);
f.append(img);
} catch (IOException e) {
e.printStackTrace();
}
TextField tf = new TextField("Email or Phone", null, 300, TextField.ANY);
f.append(tf);
TextField tf1 = new TextField("Password", null, 300, TextField.ANY);
f.append(tf1);
ChoiceGroup cg = new ChoiceGroup(null, ChoiceGroup.MULTIPLE);
cg.append("Remember Me",null);
f.append(cg);
StringItem str = new StringItem(null, "Forgot Password?", StringItem.HYPERLINK);
f.append(str);
try {
Image g2 = Image.createImage("/Fb Login 2.png");
ImageItem img2 = new ImageItem(null, null, Item.LAYOUT_CENTER, null, Item.BUTTON);
f.append(img2);
} catch (IOException e2) {
e2.printStackTrace();
}
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
}
Message in output:
Starting emulator in execution mode
* Error *
Failed to connect to device 6!
Reason:
Failed to initialize connection with emulator 6! (possible runtime incompatibility)
F:\NetBeansProjects\MobileApplication2\nbproject\build-impl.xml:782: Execution failed with error code 1.
BUILD FAILED (total time: 12 seconds)