I have created a barcode scanner with Zxing library. Once I click the scan button I am getting data from a rest endpoint. Everything works fine when I install the app on my device. It works even onBackPressed. But when I restart the app and click the scan button nothing happens and I dont even get any error or something helpful at my logs..!I realised that when I close the app and go to the info of the app on my device I see that the camera permission is turned on as it should.. but if I turn off the permission and open the app again I see the request permission dialogue again.. I choose "allow" and the camera opens..! I have tried so many suggestions that I read here but I havent managed to solve the issue.
On my ScanCodeActivity:
Intent intent = new Intent(ScanCodeActivity.this, TimelineActivity.class);
intent.putExtra("barcode", result.getText());
startActivity(intent);
onBackPressed();
}
#Override
protected void onPause() {
super.onPause();
scannerView.stopCamera();
}
#Override
protected void onPostResume() {
super.onPostResume();
if (ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA},
MY_PERMISSIONS_REQUEST_CAMERA);
}
scannerView.setResultHandler(this);
scannerView.startCamera(mCameraId);
}
On MainActivity:
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA},
MY_PERMISSIONS_REQUEST_CAMERA);
}
#Override
public void onRequestPermissionsResult ( int requestCode,
#NonNull String[] permissions,
#NonNull int[] grantResults){
super
.onRequestPermissionsResult(requestCode,
permissions,
grantResults);
if (requestCode == MY_PERMISSIONS_REQUEST_CAMERA) {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(MainActivity.this,
"Camera Permission Granted",
Toast.LENGTH_SHORT)
.show();
} else {
Toast.makeText(MainActivity.this,
"Camera Permission Denied",
Toast.LENGTH_SHORT)
.show();
}
}
FloatingActionButton myFavBtn = findViewById(R.id.myFavBtn);
myFavBtn.setOnClickListener(
this::onClick);
}
private void onClick(View view) {
startActivity(new Intent(this, ScanCodeActivity.class));
}
Part of my manifest.xml:
<activity android:name=".ui.ScanCodeActivity" />
<activity android:name=".ui.TimelineActivity" />
<activity android:name=".ui.MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity android:name=".ui.SlideActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
To give you the general view.. I have Onboarding screens which appears on the first view of the app after the installation..! Then on the main activity there is the scan button where all the main functionalities begin! Not sure if I should give you more details!!! I would appreciate it if you could give me a hint on how to deal with this issue!!! Thanks in advance!!!
Related
I'm trying to do a quick test app that allow me to turn on a off Bluetooth and I code the listeners for clicks in the buttons. This is the one that turn Bluetooth on:
mOnBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (!mBlueAdapter.isEnabled()) {
showToast("Turning On Bluetooth...");
//intent to on BT
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
//Android Studio force me to do this check.
if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
showToast("I'm stuck here");
return;
}
startActivityForResult(intent, REQUEST_ENABLE_BT);
} else {
showToast("Bluetooth is already on");
}
}
});
The thing is that Android Studio force me to add the:
if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
showToast("I'm stuck here");
return;
}
check error but even I have all the permissions they asked me in AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.BLUETOOTH_ADVERTISE" />
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
<uses-permission android:name="android.permission.BLUETOOTH_SCAN" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/Theme.Bluetooth">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
the program always fails the check error and ended up in the "You're stuck message", what is happening here?
Turning bluetooth on and requesting `BLUETOOTH_CONNECT permission is a different thing.
Request permission like BLUETOOTH_CONNECT, see https://developer.android.com/training/permissions/requesting.
Turning bluetooth on
if (bluetoothAdapter?.isEnabled == false) {
val enableBtIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT)
}
If enabling Bluetooth succeeds, your activity receives the RESULT_OK result code in the onActivityResult() callback. If Bluetooth was not enabled due to an error (or the user responded "Deny") then the result code is RESULT_CANCELED.
See Set up Bluetooth for details.
Yes, I did take a look at all other similar question but they are not working for me. I'm trying to scan all the access points near me. This exact code works for Android 10, but in Android 6.0, specifically in Galaxy J5, the getScanResult() is always returning empty, the code:
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lista_alunos);
setTitle(TITULO_APPBAR);
listaAlunosView = new ListaAlunosView(this);
configuraFabNovoAluno();
configuraLista();
wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
//Check for permissions
if ((ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED)
|| (ContextCompat.checkSelfPermission(this, Manifest.permission.CHANGE_WIFI_STATE)
!= PackageManager.PERMISSION_GRANTED))
{
Log.i("TAG", "Requesting permissions");
//Request permission
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_WIFI_STATE,
Manifest.permission.CHANGE_WIFI_STATE,
Manifest.permission.ACCESS_NETWORK_STATE},
123);
}
else
Log.i("TAG", "Permissions already granted");
wifiScan();
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
Log.i("TAG,", "onRequestPermissionsResult");
switch (requestCode)
{
case 123:
{
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
{
// permission was granted
Log.i("TAG", "permission granted: " + permissions[0]);
}
else
{
// permission denied, boo! Disable the
// functionality that depends on this permission.
Log.i("TAG", "permission denied: " + permissions[0]);
}
return;
}
// other 'case' lines to check for other
// permissions this app might request.
}
}
private void wifiScan() {
wifiManager.startScan();
BroadcastReceiver wifiScanReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
boolean success = intent.getBooleanExtra(WifiManager.EXTRA_RESULTS_UPDATED, false);
if(success) {
List<ScanResult> scanResults = wifiManager.getScanResults();
Log.i("SCAN RESULT:", "" + scanResults);
} else {
}
}
};
Android Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="br.com.alura.agenda"
tools:ignore="GoogleAppIndexingWarning">
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme"
tools:ignore="AllowBackup">
<activity android:name=".ui.activity.ListaAlunosActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".ui.activity.FormularioAlunoActivity" />
</application>
</manifest>
I also turned my Location Services ON.
Can someone tell me where is the error?
I know there are a lot of questions like this already floating around, and I've tried all that I could come across, but I still can't get it to work.
My problem is the BroadcastReceiver onReceive never seem to be called.
My code is as follows:
class SMSReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
Log.d("BroadcastReceiver", "onReceive")
if (intent.action == Telephony.Sms.Intents.SMS_RECEIVED_ACTION) {
Log.d("BroadcastReceiver", "SMS received")
// Will do stuff with message here
}
}
The log messages never show up.
AndroidManifest.xml
<uses-permission android:name="android.permission.SEND_SMS" />
<uses-permission android:name="android.permission.READ_SMS"/>
<uses-permission android:name="android.permission.RECEIVE_SMS"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/Theme.AppCompat.Light.NoActionBar">
<activity android:name=".main.MainActivity"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER"
/>
</intent-filter>
</activity>
<activity android:name=".setup.SetupActivity"
android:screenOrientation="portrait">
</activity>
<receiver
android:name=".SMSReceiver"
android:enabled="true"
android:exported="true">
<intent-filter android:priority="1000">
<action
android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
</application>
In my mainActivity I've tried multiple ways of achieving this, but currently there's only:
var smsReceiver = SMSReceiver()
I appreciate any tips I can get, and it would also be great if any code samples was written in Kotlin. :)
I got into the same issue actually it was only permissions issue even if I was requesting all permissions and allowing all at once still some permissions were not grated, make sure by applying debugging tags that you have all permissions allowed.
I used the following
private val appPermission = arrayOf(Manifest.permission.READ_SMS, Manifest.permission.RECEIVE_MMS)
in onCreate
// Here, thisActivity is the current activity
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.RECEIVE_SMS)
!= PackageManager.PERMISSION_GRANTED) {
// Permission is not granted
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.RECEIVE_SMS)) {
// Show an explanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(this,
arrayOf(Manifest.permission.RECEIVE_SMS),
PERMISSIONS_RECEIVE_SMS)
// MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
// app-defined int constant. The callback method gets the
// result of the request.
}
} else {
// Permission has already been granted
}
here is onRequestPermission
override fun onRequestPermissionsResult(requestCode: Int,
permissions: Array<String>, grantResults: IntArray) {
when (requestCode) {
PERMISSIONS_RECEIVE_SMS -> {
// If request is cancelled, the result arrays are empty.
if ((grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
// permission was granted, yay! Do the
// contacts-related task you need to do.
Log.d(TAG, "PERMISSIONS_RECEIVE_SMS permission granted")
// Here, thisActivity is the current activity
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.READ_SMS)
!= PackageManager.PERMISSION_GRANTED) {
// Permission is not granted
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.READ_SMS)) {
// Show an explanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(this,
arrayOf(Manifest.permission.READ_SMS),
PERMISSIONS_REQUEST_READ_SMS)
// MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
// app-defined int constant. The callback method gets the
// result of the request.
}
} else {
// Permission has already been granted
}
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
Log.d(TAG, "PERMISSIONS_RECEIVE_SMS permission denied")
}
return
}
PERMISSIONS_REQUEST_READ_SMS -> {
// If request is cancelled, the result arrays are empty.
if ((grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
// permission was granted, yay! Do the
// contacts-related task you need to do.
Log.d(TAG, "PERMISSIONS_REQUEST_READ_SMS permission granted")
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
Log.d(TAG, "PERMISSIONS_REQUEST_READ_SMS permission denied")
}
return
}
// Add other 'when' lines to check for other
// permissions this app might request.
else -> {
// Ignore all other requests.
}
}
}
Do not use if check inside the onReceive()
class SMSReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
Log.d("BroadcastReceiver", "onReceive")
Log.d("BroadcastReceiver", "SMS received")
// Will do stuff with message here
}
Today I got a rejection from Google for my app Facetocall
Your app does not appear to prompt the user to be a default handler prior to requesting related permissions as required by the policy.
Please make necessary changes in order to comply with policy
requirements and resubmit your app through a Declaration Form.
Default handler capability was listed on your declaration form, but your app has no default handler capability.
My goal is to make a default dialer app.
Here is my Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.gazman.beep"
android:installLocation="preferExternal">
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.READ_CALL_LOG" />
<uses-permission android:name="android.permission.WRITE_CALL_LOG" />
<uses-permission android:name="android.permission.SEND_SMS" />
... and other permissions
<application
android:name=".application.BeepApp"
android:allowBackup="false"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
tools:ignore="GoogleAppIndexingWarning">
<activity
android:name=".system_intents.IntentsActivity"
android:launchMode="singleTask"
android:noHistory="true"
android:theme="#style/Theme.Transparent">
<intent-filter>
<action android:name="android.intent.action.DIAL" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.DIAL" />
<category android:name="android.intent.category.DEFAULT" />
<data android:scheme="tel" />
</intent-filter>
</activity>
<activity
android:name=".call.CallActivity"
android:launchMode="singleTop"
android:screenOrientation="portrait"
android:showForAllUsers="true" />
<service
android:name="com.gazman.beep.call.MyInCallService"
android:permission="android.permission.BIND_INCALL_SERVICE">
<meta-data
android:name="android.telecom.IN_CALL_SERVICE_UI"
android:value="true" />
<intent-filter>
<action android:name="android.telecom.InCallService" />
</intent-filter>
</service>
... And other declarations
</application>
</manifest>
And here is what I do when my app launches:
private void checkDefaultHandler() {
if (isAlreadyDefaultDialer()) {
return;
}
Intent intent = new Intent(TelecomManager.ACTION_CHANGE_DEFAULT_DIALER);
intent.putExtra(TelecomManager.EXTRA_CHANGE_DEFAULT_DIALER_PACKAGE_NAME, getPackageName());
if (intent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(intent, REQUEST_CODE_SET_DEFAULT_DIALER);
}
else{
throw new RuntimeException("Default phone functionality not found");
}
}
private boolean isAlreadyDefaultDialer() {
TelecomManager telecomManager = (TelecomManager) getSystemService(TELECOM_SERVICE);
return getPackageName().equals(telecomManager.getDefaultDialerPackage());
}
What am I missing here?
I tried submitting the form again and this time I add a video that shows my app on an emulator(I see the same behavior on all the real devices too) here is the reply that I got back:
Your app does not appear to prompt the user to be a default handler prior to requesting related permissions as required by the policy.
Please make necessary changes in order to comply with policy
requirements and resubmit your app through a Declaration Form.
to make default dialer app, you need to do 2 things :
1. add the following permissions in your android manifest
<activity>
<intent-filter>
<action android:name="android.intent.action.DIAL"/>
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
</activity>
actually performing the check :
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.main_layout)
...
checkDefaultDialer()
...
}
const val REQUEST_CODE_SET_DEFAULT_DIALER=200
private fun checkDefaultDialer() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M)
return
val telecomManager = getSystemService(TELECOM_SERVICE) as TelecomManager
val isAlreadyDefaultDialer = packageName == telecomManager.defaultDialerPackage
if (isAlreadyDefaultDialer)
return
val intent = Intent(TelecomManager.ACTION_CHANGE_DEFAULT_DIALER)
.putExtra(TelecomManager.EXTRA_CHANGE_DEFAULT_DIALER_PACKAGE_NAME, packageName)
startActivityForResult(intent, REQUEST_CODE_SET_DEFAULT_DIALER)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
when (requestCode) {
REQUEST_CODE_SET_DEFAULT_DIALER -> checkSetDefaultDialerResult(resultCode)
}
}
private fun checkSetDefaultDialerResult(resultCode: Int) {
val message = when (resultCode) {
RESULT_OK -> "User accepted request to become default dialer"
RESULT_CANCELED -> "User declined request to become default dialer"
else -> "Unexpected result code $resultCode"
}
Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
}
You don't need to panic. This kind of conversation happened with me also, regarding AdMob content on my app. I declared everything perfectly but still they were saying content rating not fine due to type of Ads my app was showing. When more mails exchanged they sent me screenshot with the proof of wrong Ads, so finally i checked my whole code again and found my mistake.
The point here is that Google is good at what they do, and if they said so, then your app lacks something.
To be very honest, your app did not ask the user anywhere to allow it to be set as default, instead it set itself default in the background. You should ask for every permission required by your app that are critical and can be used by any app or virus or spyware to interfere with user privacy.
You can do that with a function like in the following example, which is asking for Camera permission from the user:
private void requestCameraPermission() {
Log.i(TAG, "CAMERA permission has NOT been granted. Requesting permission.");
// BEGIN_INCLUDE(camera_permission_request)
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.CAMERA)) {
// Provide an additional rationale to the user if the permission was not granted
// and the user would benefit from additional context for the use of the permission.
// For example if the user has previously denied the permission.
Log.i(TAG,
"Displaying camera permission rationale to provide additional context.");
Snackbar.make(mLayout, R.string.permission_camera_rationale,
Snackbar.LENGTH_INDEFINITE)
.setAction(R.string.ok, new View.OnClickListener() {
#Override
public void onClick(View view) {
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.CAMERA},
REQUEST_CAMERA);
}
})
.show();
} else {
// Camera permission has not been granted yet. Request it directly.
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA},
REQUEST_CAMERA);
}
// END_INCLUDE(camera_permission_request)
}
You can see the complete repository at Google Samples
And don't worry. If you rectify this problem, they will accept your application, as they did for mine.
in case anyone comes cross this post . . .
I used this for asking the user for changing the default dailer.
Know that the there gonna be 2 windows prompting(for me it was fine).
private void setDefaultDialer()
{
AlertDialog.Builder builder;
builder = new AlertDialog.Builder(this);
builder.setMessage("Do you want to make Cricket your default Dialer?(it will not cover or replace your dialer)")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
defaultDialerPackage = "cricket";
Intent intent = new Intent(TelecomManager.ACTION_CHANGE_DEFAULT_DIALER);
startActivityForResult(intent.putExtra(TelecomManager.EXTRA_CHANGE_DEFAULT_DIALER_PACKAGE_NAME,getPackageName()),REQUEST_CODE_SET_DEFAULT_DIALER);
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
Toast.makeText(getApplicationContext(),"Cancelled - No action was taken",
Toast.LENGTH_SHORT).show();
}
});
AlertDialog alert = builder.create();
alert.setTitle("Cricket need default dialer permission!!");
alert.show();
}
I am currently trying to access the GooglePlayServices. The internet for all the other functions on the AVD (API 23) works fine, however I am not quite sure what the problem is on my actual app.
Everytime I try to connect, it says that Connection has failed. I believe I have set up the GoogleAPIClient correctly, though in the ConnectionRequest, I have not customised any of the settings (for simplicity's sake).
This is some of my app's code to provide some information.
Manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:name=".Protoype2"
android:allowBackup="true"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".SettingsMenu"
android:label="#string/title_activity_settings_menu"
android:parentActivityName=".MainActivity"
android:theme="#style/AppTheme.NoActionBar">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.example.denny.protoype2.MainActivity" />
</activity>
<activity
android:name=".ViewingWindow"
android:label="#string/title_activity_viewing_window"
android:parentActivityName=".MainActivity"
android:theme="#style/AppTheme.NoActionBar">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.example.denny.protoype2.MainActivity" />
</activity>
</application>
onCreate(); from the relevant Class
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_viewing_window);
mRequestingLocationUpdates = ((Protoype2)getApplication()).getRequestingLocationUpdates();
if (!mRequestingLocationUpdates) {
StoppedMessage();
}
ExceedInstance = 0;
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this, this)
.addApi(Drive.API)
.addScope(Drive.SCOPE_FILE)
.build();
String[] LocationPermission = new String[]{Manifest.permission.ACCESS_FINE_LOCATION};
if (ContextCompat.checkSelfPermission(ViewingWindow.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(ViewingWindow.this,
Manifest.permission.ACCESS_FINE_LOCATION)) {
GPSExplanation();
} else {
ActivityCompat.requestPermissions(ViewingWindow.this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);
}
}
onRequestPermissionsResult(MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION, LocationPermission, grantResults);
final Button BackButton = (Button)findViewById(R.id.VWBackButton);
BackButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent GoBackIntent = new Intent (ViewingWindow.this, MainActivity.class);
startActivity(GoBackIntent);
}
});
updateValuesFromBundle(savedInstanceState);
}
Finally, the several predefined methods of connection:
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
public void onConnected(Bundle connectionHint) {
createLocationRequest();
if (mRequestingLocationUpdates) {
startLocationUpdates();
}
}
protected LocationRequest createLocationRequest() {
return new LocationRequest();
}
Check if your AVD has the appropriate version of the Google Play services APK, implement the onConnectionFailed() callback method. Use the parameter ConnectionResult that can be used for resolving the error, and deciding what sort of error occurred.
To resolve the error, the resolution must be started from an activity with a non-negative requestCode passed to startResolutionForResult(Activity, int). Applications should implement onActivityResult in their Activity to call connect() again if the user has resolved the issue (resultCode is RESULT_OK).
Based from this documentation, when your app receives a call to the onConnectionFailed()) callback, you should call hasResolution() on the provided ConnectionResult object. If it returns true, your app can request that the user take immediate action to resolve the error by calling startResolutionForResult() on the ConnectionResult object.
Check this related question. Hope it helps!