onDestroy() onTaskRemoved both not working on Redmi MI device - android

I'm here developed a hybrid cordova based android app in which i need to do some task before killing app for this i wrote below code onDestroy() in MainActivity and onTaskRemoved in one of service class which is calling perfectly on Samsum, Motorola, Asus etc. many device except Redmi MI Devices.
Some days back the same code was working in MI device but now its not after updating MI with MIUI 9.6.0 and above. I have tested one of MI device with MI 9.5.0 in which its working both the method but after upgrade of my device now its not working.
So is someone having the same issue? what we can do to achieve app killing event? is there any option through which it should start working or having any other way to do the same only for MI device?
I have checked over the internet and did changes for Autostart options as well still not working.
#Override
public void onTaskRemoved(Intent rootIntent) {
Log.d(getClass().getName(), "App just got removed from Recents!");
Toast.makeText(getApplicationContext(),"18. onTaskRemoved()", Toast.LENGTH_SHORT).show();
}
#Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(getApplicationContext(),"16. onDestroy()", Toast.LENGTH_SHORT).show();
}

Few OEMs including (RedMi) customizes the stack ROM for battery/memory optimization and have blocked the "onDestroy()" and "onTaskRemoved" callbacks.
As an user you can prevent the App's service from killing by locking the App.
Or, White listing the app by enabling "Autostart" setting for the App. Programmatically you can prompt the user to enable the Autostart for the App: Please find details here
Please note: I have tested the Autostart enabling programatically on few devices but found that it does not works always. So not sure how to fix in a proper way, but this solution might worked at-least up-to certain extent.

Related

Samsung 8+ does not receive any Activity Recognition events

I'm running the Google Codelab Android Activity Recognition API example on my Samsung 8+
https://codelabs.developers.google.com/codelabs/activity-recognition-transition/
And although the example starts fine on my phone, I do not get any events from the activity recognition API.
I first though that it might be a permission issue, but On Android 9 I could not find a permission setting for the ACTIVITY_RECOGNITION, this seems to be necessary for Android 10 onwards.
Could someone give a pointer what possible reasons might be that my Samsung 8+ is not getting any Activity Recognition events?
I have 2 Xiaomi phone that is running Android 9. 1 is Redmi Note 3 and is working . The other 1 is Pocophone and it is not working.
Then I tested with Samsung Galaxy Grand Prime Android 5. It is working. Now I am confused why some device it appears but some not appear.
Even registering broadcast receiver in Manifest file,you need to register in dynamically in Oreo+ otherwise it will not work.
Try this.Add this code in main activity or in startCommand in Service.It worked for me.I have tested this code on Android 10 too..worked perfectly.You dont need to register broadcast receiver in Manifest.
#Override
protected void onStart() {
super.onStart();
IntentFilter intentFilter=new IntentFilter(Constants.BROADCAST_DETECTED_ACTIVITY);
intentFilter.addCategory(Intent.CATEGORY_DEFAULT);
registerReceiver(broadcastReceiver,intentFilter);
}

Running a foreground service in Chinese ROMs

I've made a foreground service to constantly scan for BLE devices around me. For some reason it seems to work flawlessly on my stock android device Google pixel and also on Samsung S9+.
But recently I tested the app with a Chinese ROM(Oneplus 6T, Xiaomi Poco F1) the foreground service seems to be killed there after a few minutes. I've used workmanager to restart service but the app is not restarting and I get a bug report instead for the app.
Also on Chinese ROM devices below android 8.0(Xiaomi redmi 3s prime), simple service wont work, I need to use a foreground service there as well. Is there any solution to solving this?
Ask users to whitelist your app. This is the only solution. Even foreground service + wake lock won't work.
There was a discussion last month: Workmanager reliability for periodic tasks on Chinese roms (Xiaomi, Huawei, and so on). There are some useful links in there but eventually you'll have to let users whitelist your app in every ROM's specific battery optimization(or other name) settings.
A simple approach would be to ask user to put your app in non-optimized apps by opening the battery optimization settings at the starting of your app
Use below code to open the setting:
Intent batterySaverIntent=new Intent(Settings.ACTION_BATTERY_SAVER_SETTINGS);
startActivity(batterySaverIntent);
Or you can try this:
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
startForegroundService(new Intent(this, ServiceClass.class));
}

When app clear from recent apps list, background service stopped in android nougat and oreo

When I clear my app from recent apps list, my app background service killed. I tried with android nougat and oreo. But it's working in Android 6.0. After searched about the issue. Lot of people navigated the answer to Background Execution Limits.
Any one have solution for this issue?
Android Nougat should not have those issues ideally. I've spend weeks on NotificationListenerService which runs perfectly fine in background in Nougat.
It also works great in Samsung S9 (Android Oreo) but I have some issues in Google devices and emulators.
I've raised a similar issue few weeks back.
Just to make sure, enable background services for your app through console.
Also, specify which service you are using?
try this
#TargetApi(Build.VERSION_CODES.O)
private void moveToStartedState() {
Intent intent = new MyIntentBuilder(this)
.setCommand(Command.START).build();
if (isPreAndroidO()) {
Log.d(TAG, "Running on Android N or lower");
startService(intent);
} else {
Log.d(TAG, "Running on Android O");
startForegroundService(intent);
}
}
Example
https://proandroiddev.com/deep-dive-into-android-services-4830b8c9a09
Simple answer:
Use foreground services instead of background services.
Why?
Because of changes in how latest Android SDKs treat background services and Doze mode.
Good luck :)

onTaskRemoved() not getting called when Home press & kill the app

This question not duplicate of onTaskRemoved() not getting called in HUAWEI and XIOMI devices
Problem:
When I press home button & kill the app onTaskRemoved() (Service class override method) - not called.
If I press back button & kill the app --> onTaskRemoved() called perfectly
This issue happen in Android lollipop versions & oreo versions
MyService.class -> Manifest declaration
<service android:name=".MyService"
android:label="MyService"
android:stopWithTask="false"
android:enabled="true"
android:exported="true"
/>
I already used the return START_STICKY; in onStartCommand()
Tested devices
Lenovo, Samsung - lollipop version
Samsung - oreo version
Any suggestions or comments are welcome. Your small tips will help to fix this huge issue.
Based on your use case, you should be able to meet the criteria for the White listing on Android N and above. You can follow this link to Whitelist your app. By requesting this permission, you can relax some restrictions (like accessing network or holding partial lock) implied by Doze mode and Android O. These restrictions are imposed by OS on the app those are not white-listed.
For Lollipop: Certain manufacturers using cyanogenmod or other custom implementation, could have impact on the intended behavior of START_STICKY. Workaround in this case would be to rely on onDestroy() method of service to:
Restart the service.
Trigger an AlarmManager which will trigger after few seconds and start the service.
If you use approach 2:
On normal devices where the START_STICKY behaves as intended, you can use the AlarmManager to check if service is running by:
Maintain a static variable in service to check if service has been started
Cancel the AlarmManager onStartCommand() of the service.

Install referrer not working in some redmi devices

I need to track install referrals for my android app. It's working fine in most of the devices. But in Redmi device, the broadcast is not getting triggered. I tested it with Redmi Note 4
I have tested it both from via ADB as well as play store. Both don't trigger the broadcast in Redmi device
Below is the code that I am using
public class ReferrerReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Log.d("Broadcast", "RECEIVED!");
}
}
<receiver
android:name=".receiver.ReferrerReceiver"
android:exported="true">
<intent-filter>
<action android:name="com.android.vending.INSTALL_REFERRER"/>
</intent-filter>
</receiver>
Please suggest if someone faced the same issue and got some solution??
Is your app in the list of "protected apps" that are allowed to run in the background? If not, it won't get automatically started. This is a problem on devices like Xiaomi, Huawei and others. There should be a settings page in "Settings->Apps-Security" that allows you to add your app to a list of apps that are allowed to autostart, run in the background, etc. Each device manufacturer does this a bit differently, but in general we see this on Chinese devices as a way to preserve battery life.
See also:
How to get MIUI Security app auto start permission programmatically?
How to enable AutoStart option for my App in Xiaomi phone Security App programmatically in android
GCM push notifications for android devices are not working on MI and Letv mobiles
In Redmi device some android applications needs permissions. Please allow the permissions manually in the device. By using app permissions option in your device give all permissions. It may work which i had observed for my app.
There is always some issues with the miui due to their restrictions on background processes you can turn them on here is how it goes
1: Go to settings --> manage apps' battery usage --> choose apps. From there, pick all the apps you want to receive push notifications and select "No restrictions."
2: Go to settings --> permissions --> autostart. From there, pick the apps you want, and toggle the switch to turn it on.
3: Lock the app in the "recent apps"/ "app overview" plane. Do so by first opening the apps, then press the "recent apps/overview button" (that's the square button on stock Android, or the button with three horizontal lines on the Mi Mix). From there, find the app you want to receive notifications, pull down on it to "lock it", so it never gets cleared.
4: This last step requires Developer Options privileges. To enable that, go to settings (man... I'm getting tired of typing "go to settings" ...) --> about phone
tap on MIUI version tab like eight times. You should then get a little message saying "you are now a developer." Then head back out to settings, go to developer option, scroll to nearly the bottom, find "memory optimization," and turn it off.
Again, maybe step 4 is all you need.
I use Redmi 3 Pro and always have trouble with Android Permission. Xiaomi devices use custom ROM that caused permission request buggy sometimes.
The overlay service permission is always forced set to Denied in every app that I installed. I must manually Allow it.
Nice workaround I found to let Xiaomi devices auto start permission: How to get MIUI Security app auto start permission programmatically?
You could solve this issue by using the Play Install Referrer Library api 1.0 from Google. I did it this way and it works fine on devices that block the auto start by default.
First Add the following line to the dependencies section of the build.gradle file for your app:
dependencies {
...
compile 'com.android.installreferrer:installreferrer:1.0'
}
Then you should implement the interface InstallReferrerStateListener and its methods onInstallReferrerSetupFinished and onInstallReferrerServiceDisconnected in your Activity
Call the newBuilder() method to create an instance of InstallReferrerClient class.
Call the startConnection() to establish a connection to Google Play.
The startConnection() method is asynchronous, so you must override InstallReferrerStateListener to receive a callback after startConnection() completes.
You should also Override the onInstallReferrerSetupFinished() method to handle lost connections to Google Play. For example, the Play Install Referrer Library client may lose connection if the Play Store service is updating in the background. The library client must call the startConnection() method to restart the connection before making further requests.
Example:
InstallReferrerClient mReferrerClient
mReferrerClient = InstallReferrerClient.newBuilder(this).build();
mReferrerClient.startConnection(new InstallReferrerStateListener() {
#Override
public void onInstallReferrerSetupFinished(int responseCode) {
switch (responseCode) {
case InstallReferrerResponse.OK:
// Connection established
break;
case InstallReferrerResponse.FEATURE_NOT_SUPPORTED:
// API not available on the current Play Store app
break;
case InstallReferrerResponse.SERVICE_UNAVAILABLE:
// Connection could not be established
break;
}
}
#Override
public void onInstallReferrerServiceDisconnected() {
// Try to restart the connection on the next request to
// Google Play by calling the startConnection() method.
}
});
After you have established a connection to the Play Store app:
Use the synchronized getInstallReferrer() method to return ReferrerDetails.
Then, use methods in ReferrerDetails to get install timestamps and a referrer url.
ReferrerDetails response = mReferrerClient.getInstallReferrer();
response.getInstallReferrer();
response.getReferrerClickTimestampSeconds();
response.getInstallBeginTimestampSeconds();
For further info:
https://developer.android.com/google/play/installreferrer/library
Hope this helps!!

Categories

Resources