I'm relatively new to Android programming. So far, I'm working on a messaging app that will send a message via SMS and have the option to append GPS coordinates to the message. The problem I have here is with SDK version 23, the permissions need to be requested at runtime, and I have not found a good example where I can request the needed permissions before running the app. The code sample I have is below.
If I comment out this code section, Android Studio compiles the code, but I get an application crash when I tap the button that sends the message. I do have the appropriate code in my AndroidManifest.xml for using SMS and GPS permissions.
if (ContextCompat.checkSelfPermission(MainActivity,
Manifest.permission.SEND_SMS)
!= PackageManager.PERMISSION_GRANTED)
{
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity,
Manifest.permission.SEND_SMS))
{
Toast.makeText(getBaseContext(),
"Foo Messenger requires permission to send SMS",
Toast.LENGTH_SHORT).show();
}
else
{
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(MainActivity,
new String[]{Manifest.permission.SEND_SMS},
MY_PERMISSIONS_REQUEST_SEND_SMS);
}
}
if (ContextCompat.checkSelfPermission(MainActivity,
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED)
{
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity,
Manifest.permission.ACCESS_FINE_LOCATION))
{
Toast.makeText(getBaseContext(),
"Foo Messenger requires permission to access GPS to be able to send your coordinates",
Toast.LENGTH_SHORT).show();
}
else
{
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(MainActivity,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_SEND_SMS);
}
}