this is the first time I ask a question on this forum: p
I made an android application that must work in the background ie when the phone is on standby to be able to recover the location of the user. I use a service and wakelock.
The application works on SAMSUNG but I noticed that HUAWEI kills the application if it is not in the list of protected applications.
So I create a dialog box to tell the user to activate the application in the list of protected applications as shown here: Keeping a periodic service active while the phone is locked
Since my app should run on all android phones I will want to know if there are other phones brands that kill the app when the phone is idle to do the same thing please.
Thank you in advance :)
I was facing the same problem and using accessibility I tried to get the class name or activity name to pass in intent and open the settings and looks like Old Protected app list is no more available, a new way is:
disable the application from Launch in HUAWEI
tested on Oreo Huawei p10:
For Manually you can go with below steps:
Settings -> Battery -> Launch
and find your application and disable
Programmatically:
public class Constant {
public static List<Intent> POWERMANAGER_INTENTS = Arrays.asList(
new Intent().setComponent(new ComponentName("com.huawei.systemmanager", "com.huawei.systemmanager.appcontrol.activity.StartupAppControlActivity")),
new Intent().setComponent(new ComponentName("com.miui.securitycenter", "com.miui.permcenter.autostart.AutoStartManagementActivity")),
new Intent().setComponent(new ComponentName("com.letv.android.letvsafe", "com.letv.android.letvsafe.AutobootManageActivity")),
new Intent().setComponent(new ComponentName("com.coloros.safecenter", "com.coloros.safecenter.permission.startup.StartupAppListActivity")),
new Intent().setComponent(new ComponentName("com.coloros.safecenter", "com.coloros.safecenter.startupapp.StartupAppListActivity")),
new Intent().setComponent(new ComponentName("com.oppo.safe", "com.oppo.safe.permission.startup.StartupAppListActivity")),
new Intent().setComponent(new ComponentName("com.iqoo.secure", "com.iqoo.secure.ui.phoneoptimize.AddWhiteListActivity")),
new Intent().setComponent(new ComponentName("com.iqoo.secure", "com.iqoo.secure.ui.phoneoptimize.BgStartUpManager")),
new Intent().setComponent(new ComponentName("com.vivo.permissionmanager", "com.vivo.permissionmanager.activity.BgStartUpManagerActivity")),
new Intent().setComponent(new ComponentName("com.asus.mobilemanager", "com.asus.mobilemanager.entry.FunctionActivity")).setData(android.net.Uri.parse("mobilemanager://function/entry/AutoStart"))
);
}
Put below code in Your Util or Activity Class
private static boolean isCallable(Context context, Intent intent) {
List<ResolveInfo>list=context.getPackageManager().queryIntentActivities(intent,
PackageManager.MATCH_DEFAULT_ONLY);
return list.size() > 0;
}
saveUserSessionManager is a Preference, you can set your preference class instead of SaveUserSessionManager
public static void startPowerSaverIntent(Context context, SaveUserSessionManager saveUserSessionManager) {
boolean skipMessage = saveUserSessionManager.getDataByKey("skipProtectedAppCheck", false);
if (!skipMessage) {
boolean foundCorrectIntent = false;
for (Intent intent : Constant.POWERMANAGER_INTENTS) {
if (isCallable(context, intent)) {
foundCorrectIntent = true;
new AlertDialog.Builder(context)
.setTitle(Build.MANUFACTURER + " Protected Apps")
.setMessage(String.format("%s requires to be 'White list' to function properly.\nDisable %s from list.%n", context.getString(R.string.app_name), context.getString(R.string.app_name)))
.setPositiveButton("Go to settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
context.startActivity(intent);
saveUserSessionManager.storeDataByKey("skipProtectedAppCheck", true);
dialog.dismiss();
}
})
.show();
break;
}
}
}
}
How To call?
In your MainActivity in onResume method check its enable or not.
#Override
protected void onResume() {
super.onResume();
//saveUserSessionManager is just a Preference you can set your preference class instead of SessionManager
if (!saveUserSessionManager.getDataByKey("skipProtectedAppCheck", false)) {
Utils.startPowerSaverIntent(mContext, saveUserSessionManager);
}
}
Thats all :)
Holding a wakelock probably isn't what you want, since that doesn't necessarily protect your process from getting killed. The best thing you can do to increase the priority of your app's process is by making sure your Service runs in the foreground.
On Android O, the new way you get that to work is through startForegroundService(Intent)
This will put a notification in the notification tray which will tell the Android OS that your process is currently working. Then be sure to stop the service once your task is done.
For more information on Services in general, I'd check out the Service documentation. This will show you how to add the notification with the correct text.
It might also be helpful to brush up on how background processes work in Android O by checking out the Background Process documentation. If you're following that correctly (and starting in the foreground), your process should be as resilient as possible across all manufacturers.
The app I'm working on needs to run in background and uses a foreground service to this end. Starting from Android 8+ (maybe not only for these versions) many Huawei users are reporting that the app is being closed (W/O any notice) 6 7 minutes after the screen gets locked (I'm not see here and here).
Indeed, Huawei devices kill running apps by default to optimize battery consumption (cool right?). AFAIK there is no way to programmatically workaround this behavior. Many developers suggest users how to whitelist the app (see for example: Endomondo).
I'm also looking for a way to programmatically detect the optimization in order to at least warn users. Here you can find a possible solution but I haven't had time yet to give it a try.
Related
I am working on an app where one of the service needs to be running always to perform some specific operation in the background. So i am restarting the service using a Broadcast Receiver, whenever it is being killed from the task manager. So for this i am taking Autostart/Battery Optimization permission from the user to get it restarted again.
This approach is working completely fine with almost every leading device manufacturers except on ColorOS and as long as the "Autostart/Battery Optimization permission" is turned on for my app, it is working completely fine on every other devices except that on ColorOS.
The reason for this being, i am not able to redirect user to the "AutoStart" or "Battery Optimization" settings page
I have tried to open the Autostart settings Activity from my app using this code:
Intent autostartIntent = new Intent();
autostartIntent.setComponent(new ComponentName("com.coloros.safecenter", "com.coloros.safecenter.permission.startup.StartupAppListActivity"));
startActivity(autostartIntent);
Also i have tried to play with the power saving settings manually to check if in any case that is working. But nothing seems to be working anyways.
I would be looking a way to redirect user to the Autostart permission page or to the battery optimization settings page. Anyone who dealt with the similar kind of problem can suggest some solution or even workarounds for the same.
Got it working!!
I have redirected user to the app details page and there he/she need to turn on Auto Startup option. This will keep the service running on ColorOS. Below is the code to redirect user to the app details page and here the user need to turn the Auto Startup on.
if ("oppo".equalsIgnoreCase(Build.MANUFACTURER)) {
AlertDialog.Builder builder = new AlertDialog.Builder(PermissionsActivity.this);
builder.setTitle("Allow Auto-startup");
builder.setMessage("To access content on lock screen, enable ‘Allow Auto-startup’ for JiffyFeed");
builder.setPositiveButton("Allow",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
Uri.fromParts("package", getPackageName(), null));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
});
builder.setNegativeButton("Deny", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
// Do something
}
});
builder.show();
}
Additionally, i have used a workaround as well. I am using NotificationListenerService which keeps on running always, so i am restarting the service on receipt of a new notification, so every time a new notification comes up, it wakes up the service which i need to keep running always.
I am developing an android application in which I want to display the Push notification.
It has displayed well in most of the devices except Xiaomi phones (I am using Redmi Note 4). The problem that I found is, it is because of Autostart option provided by Xiomi which will be disabled by default and the user need to enable it manually.
But I wonder that some of the Android Apps I could see enabling this option without any user interaction Ex: WhatsApp. If I try reinstalling WhatsApp and see the Autostart option , it is enabled!
I am unable to convince our client by telling it is the feature of Xiomi like devices as he is pointing out some apps which is working fine like the example I have mentioned above.
This question has been asked by some other people
Add my app to AutoStart apps list in android programmatically
How to check AutoStart is enabled for our App in Xiaomi manufacturer mobile device Programmatically
But I could not see any answers for them and Posting here with the hope that someone will have an answer for this.
The autostart feature will get enabled automatically when you will download the app from playstore if xiaomi OS wants it as apps like amazon ,google IO etc are also not allowed to autostart ,In this case you have to go to Security permissions -> autostart -> then enable autostart from there.You cannot make the app autostart by code all you can do is you can show a dialog to enable auto start and take the user to the autostart activity but this is not a good option as you cannot check whether autostart is enabled or not.
This is done by Mi in MIUI8 for saving battery .This issue wasted my 2 days XD
You can refer to this article.
For xiaomi, oppo, vivo, etc. devices to Enable Autostart option programmatically
String manufacturer = android.os.Build.MANUFACTURER;
try {
Intent intent = new Intent();
if ("xiaomi".equalsIgnoreCase(manufacturer)) {
intent.setComponent(new ComponentName("com.miui.securitycenter", "com.miui.permcenter.autostart.AutoStartManagementActivity"));
} else if ("oppo".equalsIgnoreCase(manufacturer)) {
intent.setComponent(new ComponentName("com.coloros.safecenter", "com.coloros.safecenter.permission.startup.StartupAppListActivity"));
} else if ("vivo".equalsIgnoreCase(manufacturer)) {
intent.setComponent(new ComponentName("com.vivo.permissionmanager", "com.vivo.permissionmanager.activity.BgStartUpManagerActivity"));
} else if ("Letv".equalsIgnoreCase(manufacturer)) {
intent.setComponent(new ComponentName("com.letv.android.letvsafe", "com.letv.android.letvsafe.AutobootManageActivity"));
} else if ("Honor".equalsIgnoreCase(manufacturer)) {
intent.setComponent(new ComponentName("com.huawei.systemmanager", "com.huawei.systemmanager.optimize.process.ProtectActivity"));
}
List<ResolveInfo> list = getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
if (list.size() > 0) {
startActivity(intent);
}
} catch (Exception e) {
e.printStackTrace();
}
Few popular apps run in background without being killed during memory cleanup cycle (many of the popular OEMs customize the stock ROM for battery/memory optimization), because they are "White listed" by these manufactures.
For your app you can whitelist it either manually (via corresponding "settings" for the devices) or programmatically by redirecting users to the corresponding settings page to white list the app. programmatically you can do like below:
Add below permissions in the App's manifest file:`
<uses-permission android:name="oppo.permission.OPPO_COMPONENT_SAFE"/>
<uses-permission android:name="com.huawei.permission.external_app_settings.USE_COMPONENT"/>`
Redirect your to the Auto Start setting:
if (Build.BRAND.equalsIgnoreCase("xiaomi")) {
Intent intent = new Intent();
intent.setComponent(new
ComponentName("com.miui.securitycenter",
"com.miui.permcenter.autostart.AutoStartManagementActivity"));
startActivity(intent);
} else if (Build.MANUFACTURER.equalsIgnoreCase("oppo")) {
try {
Intent intent = new Intent();
intent.setClassName("com.coloros.safecenter",
"com.coloros.safecenter.permission.startup.StartupAppListActivity");
startActivity(intent);
} catch (Exception e) {
try {
Intent intent = new Intent();
intent.setClassName("com.oppo.safe",
"com.oppo.safe.permission.startup.StartupAppListActivity");
startActivity(intent);
} catch (Exception ex) {
try {
Intent intent = new Intent();
intent.setClassName("com.coloros.safecenter",
"com.coloros.safecenter.startupapp.StartupAppListActivity");
startActivity(intent);
} catch (Exception exx) {
}
}
}
}
AutoStart Reference For other OEMs
I have tested this method and it worked but the reliability is still a question as system taking time (approx 2 Min on PoccoF1 & Xiaomi devices) to restart the killed service.
But as an user we can prevent the app's background services to get killed all together as below :
Press Recent apps physical key (left side button).
Drag down the app once (select, hold & slide it down) tap on the lock icon (if the lock is in open state) to lock the app.
The app will be put in lock condition (even if you clear the background app processes by clearing, the app will keep on running).
Same way, if you want to remove it from the lock condition, just drag down again once and the lock symbol will disappear (clearing the background process will clear the app from running too).
But, With this way App's locking status will be reset on reboot on most of the devices.
EDIT:
After observing the behavior (on Xiaomi's RedmiS3, Android V6.0) of Foreground service here is the analysis:
Even after enabling the "AutoStart" programatically (via user intervention, as explained above) the service didn't restarts always (Service restarted only on few occasions, but most of the time it didn't).
Also, if I search for "AutoStart" in device settings I can't see my app there in the AutoStart list. It seems above method only providing Autostart permission but not enabling it, NOT SURE!.
And, if I add my app into "AutoStart" list via device setting, my service gets restarted (though it takes some time).
Restarting the killed service in onTaskRemoved() callback could be another option but this callback gets called in surprising way when service gets killed. This callback gets executed only when app is been closed properly by back key press. If we minimized the app (Pause state) this callback never gets called on service kill. (Looking for the reason)
Recently I found another way, the killed service could be restarted via GCM notification event. I doubt that weather the GCM works when App's gets killed on the devices or not (I need to check this and verify the behavior). But one this is for sure "These OEMs has made the programmer life hell!).
I know it is too late to share the answer but I will put my two cents here because it is very very important. I wasted my 2 days in digging this problem out. I tried all the suggested solutions as provided here but nothings seemed to be working. Below is the solution I implemented in following steps:
Step # 01
Create your foreground service as you are doing and register it accordingly in manifest. For sample purposes, I am sharing sample of service.
class MyService : Service() {
private var wakeLock: PowerManager.WakeLock? = null
override fun onBind(intent: Intent): IBinder? {
Log.d(tag!!, "Some component want to bind with the service")
// We don't provide binding, so return null
return null
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
Log.d(tag!!, "onStartCommand executed with startId: $startId")
// by returning this we make sure the service is restarted if the system kills the service
return START_STICKY
}
override fun onCreate() {
super.onCreate()
Log.d(tag!!, "The service has been created".toUpperCase(Locale.ROOT))
startForeground(1, NotificationUtils.createNotification(this))
acquireLock()
}
override fun onDestroy() {
super.onDestroy()
Log.d(tag!!, "The service has been destroyed".toUpperCase(Locale.ROOT))
Toast.makeText(this, "Service destroyed", Toast.LENGTH_SHORT).show()
}
override fun onTaskRemoved(rootIntent: Intent?) {
Log.d(tag!!, "onTaskRemoved")
val restartServiceIntent = Intent(applicationContext, this.javaClass)
restartServiceIntent.setPackage(packageName)
val restartServicePendingIntent = PendingIntent.getService(applicationContext, 1, restartServiceIntent, PendingIntent.FLAG_ONE_SHOT)
val alarmService = applicationContext.getSystemService(ALARM_SERVICE) as AlarmManager
alarmService[AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + 1000] = restartServicePendingIntent
super.onTaskRemoved(rootIntent)
}
#SuppressLint("WakelockTimeout")
private fun acquireLock() {
// we need this lock so our service gets not affected by Doze Mode
wakeLock =
(getSystemService(Context.POWER_SERVICE) as PowerManager).run {
newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MyService::lock").apply {
acquire()
}
}
}
}
NOTE: I have covered all the possible use cases to restart the Service in case it gets killed by OS. There is one thing left if user restarts cell phone. This case can be found via other stackoverflow answers very easy. In Broadcast one just needs to start Service.
Step # 02
Make an application and register in manifest. And add below line of code in your application class.
class MyApplication : Application() {
override fun onCreate() {
super.onCreate()
val receiver = ComponentName(this, MyService::class.java)
val pm = packageManager
pm.setComponentEnabledSetting(
receiver,
PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
PackageManager.DONT_KILL_APP
)
}
}
Here, MyService is the component name and this can be Service or Broad cast Receiver you are already using in you app. In my case I trie with Android service
Now, this is the time to register this Application class in Manifest file. Open the manifest file and in application tag use property name and place your application class name which was just created MyApplication.
Step # 03
There is no third step. You are done. You just install the apk and by this way Service will not killed even the app is killed. I tested the above solution on Vivo device and it worked
NOTE: In case, above solution does not work, please check the manifest file for allowBackup property if you find out this property in manifest file just remove it and uninstall the app and then install the app it will work for sure and then you can set that property again.
As far as I know, WhatsApp is whitelisted on the Xiaomi device autostart. There is nothing you can do about it. Of course your application will be whitelisted by Xiaomi if it eventually garnered as much as WhatsApp popularity. Until that happens, you can only asking for user to activate it manually by showing the Auto-start feature with something like this:
try {
Intent intent = new Intent();
if ("xiaomi".equalsIgnoreCase(android.os.Build.MANUFACTURER)) {
intent.setComponent(new ComponentName("com.miui.securitycenter",
"com.miui.permcenter.autostart.AutoStartManagementActivity"));
}
// context is your Context
List<ResolveInfo> list = context.getPackageManager()
.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
if (list.size() > 0) {
context.startActivity(intent);
}
} catch (Exception e) {
Log.d("PERMISSION", e.toString());
}
Please note, that I haven't test the code for current Xiaomi device.
I have two apps that both have kiosk mode enabled. I currently send a broadcast from one to the other that transmits data. I want to tell the receiving app to start a new activity.
In most cases I would be able to use intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); however... I am not able to start a new task while in kiosk mode.
Here is what I have in the broadcastReceiver(which I have verified works for other data). This code tries to start a new activity:
Intent launchIntent = new Intent(Intent.ACTION_MAIN);
launchIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // this doesn't work in kiosk mode...
launchIntent.setComponent(new ComponentName("my.package","my.package.myactivity"));
try {
if(launchIntent != null) {
context.getApplicationContext().startActivity(launchIntent);
Log.i(TAG, "Started activity");
} else
Log.i(TAG, "Intent is null");
} catch (Exception e) {
Log.e(TAG, e.toString());
}
My error before adding the flag:
Kiosk Mode: Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?
And after adding the flag:
E/ActivityManager( 470): Attempted Lock Task Mode violation
Is it possible to send a context through a broadcast receiver, perhaps, so that I can start the desired activity using that context? Can anyone suggest another method other than using broadcasts to start new activity?
Note: In Android "ScreenPinning", "Kioskmode" and "Lock Task Mode" are the same.
from https://developer.android.com/about/versions/android-5.0.html#ScreenPinning
Once your app activates screen pinning, users cannot (...)
access other apps (...) until your app exits the mode.
You have to temprary disable the kioskmode with stopLockTask() interact and re-enable it with startLockTask()
To prevent android from asking the user to re-start kioskmode you also need to implement a https://developer.android.com/about/versions/android-5.0.html#DeviceOwner app
You can find a lot of infos about this topic at https://github.com/Tuong-Nguyen/Android/wiki/Research-114-Kiosk-Mode-Android-application
I am able to create an Activity that uses the DevicePolicyManager API's.
The tutorials show that I need use it the following fashion:
if (!mDPM.isAdminActive(mAdminName)) {
Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, mAdminName);
intent.putExtra("wipe-data", DeviceAdminInfo.USES_POLICY_WIPE_DATA);
startActivityForResult(intent, REQUEST_ENABLE);
}
else {
mDPM.wipeData(0);
}
However I would like this to run inside a Service.
But I cant call
startActivityForResult
from within a Service.
So what would be the best approach or strategy for me to try ?
The only reason you need to call startActivityForResult() is if your app is not presently configured as a device administrator, to lead the user to go set that up for you. Hence, put that portion of your logic inside of your user interface.
Your service itself would just skip doing anything if isAdminActive() returns false.
I have an app that include both a complex service and activity UI. The app runs on multiple devices which communicate with each other over WIFI via the service.
Since the app is a prototype/in-development, I want to add support for a "force restart" that will kill the app and re-launch it clean. There is a lot of shared UI stuff that has gotten gummed up depending on the use case, and it would be easier during testing (I have multiple devices) if I could just touch a button to restart the app completely.
So, does anyone have any suggestions on how to:
1) Force close/stop/kill your own app, from within your app.
2) Set a timer/intent that tells the OS to launch your app before you close/stop/kill it.
Any tips would be appreciated! Thank you.
Use the below code for restart the app:
Intent mStartActivity = new Intent(HomeActivity.this, SplashScreen.class);
int mPendingIntentId = 123456;
PendingIntent mPendingIntent = PendingIntent.getActivity(HomeActivity.this, mPendingIntentId, mStartActivity,
PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager mgr = (AlarmManager) HomeActivity.this.getSystemService(Context.ALARM_SERVICE);
mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, mPendingIntent);
System.exit(0);
As you can figure out, finish() is what you want to use in order to kill off an activity. A.C.R.'s way would work, however it will only restart your activity, not really kill off the process, and start it back up. If that's what you are looking for, instead of having a dummy Activity that restarts your original Activity, the correct way to do it would be to use flags.
Intent i = new Intent(this, WrapperActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
Those flags will clear your back stack all the way down to the first instance of whatever Activity you are creating, it will kill it, and then create a new one. This is essentially what A.C.R's example is doing, but it's much more concise.
If this isn't good enough for you, In order to do this properly, it's quite a bit of work, and requires more advanced knowledge of the Android system. You'd want to create a service that's running in the background (will need to be a separate process if you want the application level state killed) that you could startup when you wanted to kill the app, have the app kill itself, or have the service kill the app for you, and then have the service launch an intent that would start your activity/application back up.
Hope this helps! Best of luck!
To restart my app, I'm simple doing this and it's working:
Intent i = context.getPackageManager().getLaunchIntentForPackage(context.getPackageName());
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
System.exit(0);
If I don't use both flags, it won't work.
(Using Android 11, API 30, Pixel 3 device)
Try the below code for restarting the application.
Intent i = getBaseContext().getPackageManager()
.getLaunchIntentForPackage(getBaseContext().getPackageName());
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
Here is what you need to do:
Create a sticky Service
Kill the app with killProcess call from the Service
The sticky Service will then restart, and you can open your app with an getLaunchIntentForPackage intent
I like to use a Handler to do this off the main UI thread:
private void scheduleForceClose() {
final Handler closeAppHandler = new Handler();
closeAppHandler.post(new Runnable() {
#Override public void run() {
prefs.edit().putBoolean(StringConstants.FORCE_CLOSED_APP, true).commit();
Log.i(TAG, "Gonna force kill the app process completely!");
System.exit(0);
android.os.Process.killProcess(android.os.Process.myPid());
}
});
}
private void scheduleForceOpen() {
final Handler openAppHandler = new Handler();
taskOpenApp = new TimerTask() {
#Override public void run() {
openAppHandler.post(new Runnable() {
#SuppressLint("ApplySharedPref") #Override public void run() {
Intent intent = getPackageManager().getLaunchIntentForPackage("com.company.yourpackagename");
// Reset the force-close flag so that the close timer can begin again
prefs.edit().putBoolean(StringConstants.FORCE_CLOSED_APP, false).commit();
startActivity(intent);
}
});
}
};
// Decide whether we already force-closed the app, so that we don't repeat it
boolean alreadyForceClosed = prefs.getBoolean(StringConstants.FORCE_CLOSED_APP, false);
if (alreadyForceClosed) {
Log.i(TAG, "App process has already been killed, so schedule app relaunch.");
Timer timerOpen = new Timer();
timerOpen.schedule(taskOpenApp, 5000 /* reopen the app after 5 sec */);
}
}
No can do. The operating system decides when to kill an application. Your app can come back to life whether it was truly dead or just hidden.
This is inconvenient, but the platform works like that. You can produce the same user-facing effect by managing your activities, which you can kill and restore.
There might be a more official way to do this, but here's how I would accomplish this.
For example I am going to pretend there are only two Activities, the one you're currently in (I'll call it FirstActivity), and another "helper" Activity (I'll call SecondActivity).
In the first one (the one you want to restart it from), you would have a button that initiates the restart of the app.
restartButton.setOnClickListener(new OnClickListener(){
#Override
onClick(View v){
//when clicked it starts the helper activity and closes the one you're in
startActivity(new Intent(this, SecondActivity.class));
finish(); //or you could use FirstActivity.onDestroy(); if you want it completely dead
}
});
Second Activity: It's entire purpose is so you can basically restart your app from your app (close everything else and then restart it in this)
Class SecondActivity extends Activity{
#Override
onCreate(Bundle savedInstanceState){
...
//it restarts the old activity so it's new and ends this one
startActivity(new Intent(this, FirstActivity.class));
finish(); //or you could use SecondActivity.onDestroy(); if you want it
}
}
That will completely restart the first activity. I'm not sure if it will be as thorough as you wish, but there really isn't another way to do this sort of thing AFAIK.