Application run first time after ask location permission but when run on second time it stuck - location

Need help,
Application run first time accurately with ask permission activity, but on second run it stuck on permission activity view and don't skip the activity and shows only content of the Location Activity,
How can i achieve this?
My scenario:
1st time run- From Splash Screen----->Location Permission Activity--->Main Activity
2nd time rum From Splash Screen----->(App)Main Activity
**
Below is my code in Android Studio Java**
#Override
protected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);
setContentView(R.layout.activity_location);
if (ContextCompat.checkSelfPermission(Location.this,
Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED){
if (ActivityCompat.shouldShowRequestPermissionRationale(Location.this,
Manifest.permission.ACCESS_FINE_LOCATION)){
ActivityCompat.requestPermissions(Location.this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
}else{
ActivityCompat.requestPermissions(Location.this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions,
int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case 1: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (ContextCompat.checkSelfPermission(Location.this,
Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)
{
Toast.makeText(this, "Permission Granted", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(this, "Permission Denied", Toast.LENGTH_SHORT).show();
}
startActivity(new Intent(getApplicationContext(), MainActivity.class));
finish();
return;
}
}
}
}

Related

How do I get LocationManager.addNmeaListener() to work?

Here are the relevant parts of my code:-
public class MainActivity extends Activity
implements SensorEventListener, OnNmeaMessageListener {
private LocationManager m_locationManager;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ac = this;
m_locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
}
...
protected void onResume() {
...
if (m_locationManager != null) {
m_gpsSensor = new SensorView(this);
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
m_locationManager.addNmeaListener(getMainExecutor(), this);
} else {
// no-op in later versions
m_locationManager.addNmeaListener(this);
}
m_gpsSensor.lineBreak("gps: ", "no messages yet");
} catch (Exception ignore) {
m_gpsSensor.lineBreak("gps: ", getString(R.string.permissiondenied));
}
topLayout.addView(m_gpsSensor);
}
}
#Override
public void onNmeaMessage(String message, long timestamp) {
long nanos = timestamp * 1000000;
if (nanos > m_gpsSensor.lastNanos + UPDATE_NANOS) {
m_gpsSensor.lastNanos = nanos;
m_gpsSensor.lineBreak("gps: ", message);
}
}
}
onNmeaMessage is never called (lastNanos is initialised to zero) and m_gpsSensor (a subclass of View) displays "no messages yet". My device does have GPS, and the app has permission to access it (otherwise it would display "Permission denied"), and GPS does work, because it can see satellites and get a fix with Satstat
I tried
addNmeaListener (OnNmeaMessageListener listener, Handler handler)
which doesn't work either. m_locationManager isn't null, because in that case it wouldn't display anything at all.
The device is a Samsung Galaxy S21 Ultra 5G running Android 12.
What am I doing wrong?
Apparently addNmeaListener doesn't start the GPS, and there doesn't seem to be an explicit call to do so. You have to call one of the requestLocationUpdates variants.

OnResume() and OnSleep() called but not working properly

I'm a new Xamarin developper and I'm trying to build an app with Xamarin.Forms. Everything works properly on the app but I noticed a strange behaviour : be it on device or with the emulator, when I turn the power off one time then on again, OnSleep() and OnResume() methods work just fine.
But the problem is, when I repeat the same operation a second time, the application freezes and to unlock it I have to either close the app and open it again or go to menu where you can select other apps working in background (I don't know how it's called) and return on the app. I checked with breakpoints and those two methods are called on the first and second time. I tried removing everything from those methods but the problem persists. Does anyone know why it behaves like that ? Thank you.
In my App.xaml.cs :
protected override void OnStart()
{
if (isLoggedIn())
{
MainPage = new NavigationPage(new MDPage());
GeneralViewModel general = new GeneralViewModel();
general.checkUser();
}
else
{
MainPage = new NavigationPage(new LoginPage());
}
}
protected override void OnSleep()
{
// Handle when your app sleeps
}
protected override void OnResume()
{
if (isLoggedIn()) //With a breakpoint, this is executed
{
MainPage.Navigation.PushAsync(new MDPage());
/*this is also executed but the second time,
*even if it is executed the application freezes*/
GeneralViewModel general = new GeneralViewModel();
general.checkUser();
}
else
{
MainPage = new NavigationPage(new LoginPage());
}
}
public bool isLoggedIn()
{
if (Settings.GeneralSettings != null && Settings.GeneralSettings != "")
{
return true;
}
else
{
return false;
}
}
The GeneralViewModel method I call (btw even without it the problem persists)
public void DoSomething()
{
ThreadPool.QueueUserWorkItem(o => checkUser());
}
public Task checkUser()
{
if (Settings.GeneralSettings != null && Settings.GeneralSettings != "")
{
DoSomething();
}
else
{
try
{
var data = Application.Current.MainPage;
Device.BeginInvokeOnMainThread(async () =>
{
await data.DisplayAlert("Information(s)", "Vous avez été déconnecté", "OK");
});
}
catch (Exception e)
{
Console.WriteLine("exception");
}
}
return default;
}
edit : I checked the console and it seems even though nothing appears on the screen, when I press a button on my frozen page the action the button should do happens but the screen doesn't change.

Xamarin.Forms - Android : OnRequestPermissionsResult is never called

Under Android I need some permissions to use the Google-Map API. I use the PermissionsPlugin :
https://www.nuget.org/packages/Plugin.Permissions/
Here some code :
async void RequestPermissions()
{
var status = await CrossPermissions.Current.CheckPermissionStatusAsync(Permission.Location);
if (status != PermissionStatus.Granted)
{
if (await CrossPermissions.Current.ShouldShowRequestPermissionRationaleAsync(Permission.Location))
{
//NavigationHelper.CurrentPage.DisplayAlert("Need location", "Gunna need that location", "OK");
}
var results = await CrossPermissions.Current.RequestPermissionsAsync(Permission.Location);
//Best practice to always check that the key exists
if (results.ContainsKey(Permission.Location))
status = results[Permission.Location];
}
}
public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
{
PermissionsImplementation.Current.OnRequestPermissionsResult(requestCode, permissions, grantResults);
//base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
}
But I also noticed that the method "OnRequestPermissionsResult" is never called, and there is no dialog that ask me for permissions !!
Also, the permissions are in the manifest file too !
Any idea to solve this ?

Reading Sim Number in Dual Sim Phone Xamarin.Form

Im always getting an error of Java.Lang.SecurityException: getLine1NumberForDisplay: Neither user 10710 nor current process has android.permission.READ_SMS. Even if I already Added the READ_SMS in AndroidManifest.xml
MyCode:
public string GetNumber()
{
TelephonyManager telephonyManager = (TelephonyManager)GetSystemService(TelephonyService);
return telephonyManager.Line1Number;
}
Thanks in Advance and Good Day :D
This is a really simple runtime permission request example.
I would highly recommend reading the Xamarin blog post and the Android doc linked below as you should show the user "why" you are requesting permission before the system dialog shows up.
[Activity(Label = "RunTimePermissions", MainLauncher = true, Icon = "#mipmap/icon")]
public class MainActivity : Activity
{
const int PermissionSMSRequestCode = 99;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.Main);
Button button = FindViewById<Button>(Resource.Id.myButton);
button.Click += delegate {
if ((int)Build.VERSION.SdkInt < 23) // Permissions accepted by the user during app install
DoSomeWork();
var permission = BaseContext.CheckSelfPermission(Manifest.Permission.ReadSms);
if (permission == Android.Content.PM.Permission.Granted) // Did the user already grant permission?
DoSomeWork();
else // Ask the user to allow/deny permission request
RequestPermissions(new string[] { Manifest.Permission.ReadSms }, PermissionSMSRequestCode);
};
}
public override void OnRequestPermissionsResult(int requestCode, string[] permissions, Android.Content.PM.Permission[] grantResults)
{
base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == PermissionSMSRequestCode)
{
if ((grantResults.Count() > 0) && (grantResults[0] == Android.Content.PM.Permission.Granted))
DoSomeWork();
else
Log.Debug("PERM", "The user denied access!");
}
}
protected void DoSomeWork()
{
Log.Debug("PERM", "We have permission, so do something with it");
}
}
Ref: Requesting Runtime Permissions in Android Marshmallow
Ref: Requesting Permissions at Run Time

Google Drive API implementation Xamarin Android

Our application should have the functionality to save Application files to Google Drive. Of course, using the local configured account.
From Android API i tried to figure out some clue. But android API with Xamarin implementation seems very tough for me.
I have installed Google Play Services- Drive from Xamarin Components but there are no examples listed from which we can refer the flow and functionality.
The basic steps (see the link below for full details):
Create GoogleApiClient with the Drive API and Scope
Try to connect (login) the GoogleApiClient
The first time you try to connect it will fail as the user has not selected a Google Account that should be used
Use StartResolutionForResult to handle this condition
When GoogleApiClient is connected
Request a Drive content (DriveContentsResult) to write the file contents to.
When the result is obtained, write data into the Drive content.
Set the metadata for the file
Create the Drive-based file with the Drive content
Note: This example assumes that you have Google Drive installed on your device/emulator and you have registered your app in Google's Developer API Console with the Google Drive API Enabled.
C# Example:
[Activity(Label = "DriveOpen", MainLauncher = true, Icon = "#mipmap/icon")]
public class MainActivity : Activity, GoogleApiClient.IConnectionCallbacks, IResultCallback, IDriveApiDriveContentsResult
{
const string TAG = "GDriveExample";
const int REQUEST_CODE_RESOLUTION = 3;
GoogleApiClient _googleApiClient;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.Main);
Button button = FindViewById<Button>(Resource.Id.myButton);
button.Click += delegate
{
if (_googleApiClient == null)
{
_googleApiClient = new GoogleApiClient.Builder(this)
.AddApi(DriveClass.API)
.AddScope(DriveClass.ScopeFile)
.AddConnectionCallbacks(this)
.AddOnConnectionFailedListener(onConnectionFailed)
.Build();
}
if (!_googleApiClient.IsConnected)
_googleApiClient.Connect();
};
}
protected void onConnectionFailed(ConnectionResult result)
{
Log.Info(TAG, "GoogleApiClient connection failed: " + result);
if (!result.HasResolution)
{
GoogleApiAvailability.Instance.GetErrorDialog(this, result.ErrorCode, 0).Show();
return;
}
try
{
result.StartResolutionForResult(this, REQUEST_CODE_RESOLUTION);
}
catch (IntentSender.SendIntentException e)
{
Log.Error(TAG, "Exception while starting resolution activity", e);
}
}
public void OnConnected(Bundle connectionHint)
{
Log.Info(TAG, "Client connected.");
DriveClass.DriveApi.NewDriveContents(_googleApiClient).SetResultCallback(this);
}
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
base.OnActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE_RESOLUTION)
{
switch (resultCode)
{
case Result.Ok:
_googleApiClient.Connect();
break;
case Result.Canceled:
Log.Error(TAG, "Unable to sign in, is app registered for Drive access in Google Dev Console?");
break;
case Result.FirstUser:
Log.Error(TAG, "Unable to sign in: RESULT_FIRST_USER");
break;
default:
Log.Error(TAG, "Should never be here: " + resultCode);
return;
}
}
}
void IResultCallback.OnResult(Java.Lang.Object result)
{
var contentResults = (result).JavaCast<IDriveApiDriveContentsResult>();
if (!contentResults.Status.IsSuccess) // handle the error
return;
Task.Run(() =>
{
var writer = new OutputStreamWriter(contentResults.DriveContents.OutputStream);
writer.Write("Stack Overflow");
writer.Close();
MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
.SetTitle("New Text File")
.SetMimeType("text/plain")
.Build();
DriveClass.DriveApi
.GetRootFolder(_googleApiClient)
.CreateFile(_googleApiClient, changeSet, contentResults.DriveContents);
});
}
public void OnConnectionSuspended(int cause)
{
throw new NotImplementedException();
}
public IDriveContents DriveContents
{
get
{
throw new NotImplementedException();
}
}
public Statuses Status
{
get
{
throw new NotImplementedException();
}
}
}
Ref: https://developers.google.com/drive/android/create-file

Resources