I am building an application that should be able to close other android applications. In this case, I am using Google Maps. I have granted permission in the Android Manifest XML to killBackgroundProcesses, but the following code does not close the "Google Maps" application. My app calls killApp() every second to ensure Google Maps is closed. Any idea what I'm doing wrong here?
public void KillApp()
{
Context context = getContext();
String maps = "com.google.android.apps.maps";
ActivityManager activityManager = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);
activityManager.killBackgroundProcesses(maps);
}
You can only kill your own apps, e.g. the ones running in the same process or with the same userID. You can not kill others, unless the device is rooted.No one can kill process except Android OS itself.
Most of the task killer in android market don't kill the app they just restart the process
by using
public void restartPackage (String packageName)
when this method is called by your activity the operating system immediately called
savedInstanceState and save the state of that activity you want to kill. Now this process is
removed from memory and OS saved it state.Now when next time user start that activity it
will start from where it was killed or in other words restarted. You can verify it from any
task manager that they don't kill the process because no one can do so. This method also
work in ICS.
for above method you can look at here . As far as i know killBackgroundProcesses (String packageName) is for API 8 and above.
Related
I've been using onTaskRemoved() method in a Service to detect when an app was removed from the device's RECENT list by swiping it away. I preform some logging and some other operations that need to take place when this happens. It works perfectly. For android below 6... But background service is being killed after swiping off in android 6.
#Override
public void onTaskRemoved(Intent rootIntent) {
Log.e("ClearFromRecentSsss", "sttttts");
Intent intent = new Intent("in.com.example");
sendBroadcast(intent);
}
Some manufactures like xiaomi, Oppo have their own background strategy which is autostart. You need to redirect user to auto start activity and tell user to switch on:
Go like this and allow your app to autostart:
Settings > permissions > Autostart
Autostart setting varies by manufactures like in Xiaomi you can find it in their SecurityCenter app.
Autostart is blocking your service to restart, So turn it on manually and the check again . I'm afraid there is no inbuilt API to do so . So you need to redirect users to specified screen as per manufactures to turn auto start On. Have a look at Links below:
link1
link2
Hi i am running a background service using alaram manager its working fine but for some mi devices background service is not working.I used sevices but it is not working how to run my background service in mi ?
MI UI has its own security options, so what you need to is not just above mentioned sticky Service,
you need to
Enable Autostart
go to power setting make changes as per these youtube videos
https://www.youtube.com/watch?v=-Ffgir-QgsU, or refer for this for more suggestions
https://www.quora.com/How-do-I-keep-an-app-running-in-the-background-in-MIUI
then you have created a custom broadcast receiver which will start the service when your service is destroyed
as per this example https://fabcirablog.weebly.com/blog/creating-a-never-ending-background-service-in-android
If the 3rd option doesn't work onDestroy recall of the service call the custom broadcast receiver on
w
public void onTaskRemoved(Intent rootIntent) {
super.onTaskRemoved(rootIntent);
Log.e(TAG, " In recieve Custome Broadcast receiver");
Intent broadcastIntent = new Intent("ac.in.ActivityRecognition.RestartSensor");
sendBroadcast(broadcastIntent);
}
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.setComponent(new ComponentName("com.android.settings","com.android.settings.Settings$HighPowerApplicationsActivity"));
startActivity(intent);
try this code
it will open one setting page
then find your app and then tap "Don't Optimize"
it will turn off battery optimization and your background services run without problem
When you start a service by extending an Service class than you will get the call inside OnStartCommand() this method has three types of return type on the basis of this return type operating system itself manage when to start a service.
So suppose if your service gets killed in between due to low memory or any other issue when you return a correct type from onStartCommand() than os will take care of when to start service again.
Three return types are:
START_STICKY : When this is the return type than os takes the guarantee to restart the service again if its get killed it will definitely start you service again even if there is no pending intent it will start the service by passing intent as null.
START_NOT_STICKY: says that, after returning from onStartCreated(), if the process is killed with no remaining start commands to deliver, then the service will be stopped instead of restarted. This makes a lot more sense for services that are intended to only run while executing commands sent to them. For example, a service may be started every 15 minutes from an alarm to poll some network state. If it gets killed while doing that work, it would be best to just let it be stopped and get started the next time the alarm fires.
START_REDELIVER_INTENT is like START_NOT_STICKY, except if the service's process is killed before it calls stopSelf() for a given intent, that intent will be re-delivered to it until it completes (unless after some number of more tries it still can't complete, at which point the system gives up). This is useful for services that are receiving commands of work to do, and want to make sure they do eventually complete the work for each command sent.
I have an APK file that it requires on Internet connection. But when I click the Home button it loses its connection and can't use the Internet in onPause mode. How can I change the onPause method to do what I want in my application without losing the connection?
For example, I want it to click somewhere to unlock something in a specific time in my app. But at that time I'm sleeping and I can't do that. I just can put my app in onPause mode when I'm sleeping and make a schedule to do my favor.
You better should use Service class for your task. Then kill it calling
stopSevice(getApplicationContext(), YourService.class);
It won't stop unless Android system kill it or You kill it.
For example:
Suppose, you want to download a picture from internet with a button click. Now to download a picture you code a service class.
DownLoadPicture.class
public class DownLoadPicture extends Service
#Override
private void onCreate(){
//Download your picture now here
}
And when your picture is downloaded then just kill your service calling
stopSelf();
Or, you can kill the service from your MainActivity. To kill the service from your MainActivity call
stopService(getApplicationContext(), DownLoadPicture.class);
So, now as you are saying that when your app goes on onPause then you lost internet connection. For solving this:-
Put all your codr in the DownLoadPicture class's onCreate method that you put in your MainActivity to do your internet task. And I hope you won't lost your internet connection then.
And then on your MainActivity's onCreate method put:-
startService(getApplicationContext, DownLoadPicture.class);
And now once your service is started then it won't stop unless you own or Android system kill it
I am trying to build a task killer type of app in android. I can show the list of currently running task using ActivityManager but facing problem in killing the task.
Here is what i am doing to get the list of currently running task :
ActivityManager am = (ActivityManager) context.
getSystemService(Activity.ACTIVITY_SERVICE);
List<RunningTaskInfo> a = am.getRunningTasks(Integer.MAX_VALUE);
PackageManager pack = this.getPackageManager();
for(int i = 0; i < a.size(); i++) {
String packageName = a.get(i).topActivity.getPackageName();
Drawable d = null;
String appName = "";
try {
d = pack.getApplicationIcon(packageName);
appName = (String)pack.getApplicationLabel(pack.getApplicationInfo(packageName,PackageManager.GET_META_DATA));
} catch (NameNotFoundException e) {
e.printStackTrace();
}
packName.add(packageName); //arraylist of package name
apps.add(appName); // arraylist of app name
icons.add(d); //arraylist of icons
}
It worked for me But now as I am trying to kill the task using killBackgroundProcesses :
am.killBackgroundProcesses(package name);
It did not work . Also killBackgroundProcesses method is available in API level 2.2 then how can i perform the same task in previous API level such as 1.6 etc.
Is there any other way to show the currently active apps and kill them?
No one can kill process except Android OS itself.
Most of the task killer in android market don't kill the app they just restart the process
by using
public void restartPackage (String packageName)
when this method is called by your activity the operating system immediately called
savedInstanceState and save the state of that activity you want to kill. Now this process is
removed from memory and OS saved it state.Now when next time user start that activity it
will start from where it was killed or in other words restarted. You can verify it from any
task manager that they don't kill the process because no one can do so. This method also
work in ICS.
for above method you can look at here . As far as i know killBackgroundProcesses (String packageName) is for API 8 and above.
In a nutshell, Automatic Task Killers work by polling the OS for a list of currently running processes and the memory they are consuming. Then either with an intelligent algorithm or with user input the Task Killers issue a call to the system telling the system to kill the process. There are two apis you can do this.
They are
Process.sendSignal(pid, Process.SIGNAL_KILL);
ActivityManager.killBackgroundProcesses(PackageName)
This first works by invoking Process.killProcess(int pid) where pid is the unique identifier for a specific process. Android kills processes in the same way that linux does; however, a user may only kill processes that they own. In Android each app is run with a unique UID, user ID. So using this API an App can only kill its own processes, hence the following explanation in the docs for Process.killProcess(int pid):
Kill the process with the given PID. Note that, though this API allows
us to request to kill any process based on its PID, the kernel will
still impose standard restrictions on which PIDs you are actually able
to kill. Typically this means only the process running the caller's
packages/application and any additional processes created by that app;
packages sharing a common UID will also be able to kill each other's
processes.
When this method is called the signals is generated by the OS and set to the process. Whenever a process receives a signal from the OS it must either handle that signal or immediately die. Signals such as SIG_KILL cannot be handled and result in the immediate death of the recipient process. If you want to kill processes that you don't have privileges to kill, i.e. its not your process, then you must escalate your privileges using sudo (this would require root privileges on the device).
The second API works by telling the ActivityManager that you wan to kill processes associated with a specific Package. This API gets around the need for your UID to match the UID of the process because it requires the user to accept the KILL_BACKGROUND_PROCESSES permission. This permission signals to the OS that an app has been approved by the user as a task killer. When a task killer wants to kill an app, it tells the OS to do it getting around the problem of only being able to kill processes that you own.
In the Android Docs it says that this API actually uses the first Process.killProcess API
Have the system immediately kill all background processes associated
with the given package. This is the same as the kernel killing those
processes to reclaim memory; the system will take care of restarting
these processes in the future as needed.
Hope It Helps.
Did you enter below permission in the manifest file?
<uses-permission android:name="android.permission.GET_TASKS"/>
<uses-permission android:name="android.permission.KILL_BACKGROUND_PROCESSES"/>
I have been developing an app, and I need to close another app in my code. Does anyone know any api to call to close an app?
BTW: my app will be pre-installed.
thanks
Since Android 2.2 (i.e. going forward), you can only close the background processes of other apps, you are no longer able to close their main activities.
If your app is targeting Android <2.2, look atandroid.permission.RESTART_PACKAGE.
If you want it to work properly on 2.2 and above (which you should :-)), look at android.permission.KILL_BACKGROUND_PROCESSES, but again, this only closes background services and such and might "mess up" the other app rather than doing any good.
With the right permissions, you can then do the following:
private ActivityManager am = (ActivityManager) this.getSystemService(ACTIVITY_SERVICE);
am.restartPackage("com.jimmy.appToBeClosed");
Try This
ActivityManager am = (ActivityManager) getApplicationContext().getSystemService("activity");
Method forceStopPackage;
forceStopPackage =am.getClass().getDeclaredMethod("forceStopPackage",String.class);
forceStopPackage.setAccessible(true);
forceStopPackage.invoke(am, pkg);
In manifest file add this
<uses-permission android:name="android.permission.FORCE_STOP_PACKAGES"></uses-permission>
If both applications are yours, you can use AIDL for inter-process communication to send a message telling the other application to close. See http://developer.android.com/guide/developing/tools/aidl.html.
I have been able to close another app on Android 12 successfully. Here is how:
Basically, I am closing another app from a service although you should be able to do it from an app too.
My service is a privileged system app that gets installed in system/priv-app/ (It has LOCAL_PRIVILEGED_MODULE := true in its Android.mk)
I added <uses-permission android:name="android.permission.FORCE_STOP_PACKAGES" /> in AndroidManifest.xml
I added in privapp-permissions.xml
<privapp-permissions package="<my service package name>">
<permission name="android.permission.FORCE_STOP_PACKAGES"/>
</privapp-permissions>
I called in my service this method with the package name of the application I want to close:
private void closePackageApp(String namePackage) {
ActivityManager activityManager = (ActivityManager)
context.getSystemService(Context.ACTIVITY_SERVICE);
try {
Method forceStopPackage = activityManager.getClass().
getDeclaredMethod("forceStopPackage", String.class);
forceStopPackage.setAccessible(true);
forceStopPackage.invoke(activityManager, namePackage);
} catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
e.printStackTrace();
}
}
I tested this and in the logs, I can see the app is being closed. However the app is not removed from the recent screen (logs suggested the app was disposed without first being removed with the input manager!).
However, I am sure the app was really being closed when it was in the background by comparing its lifecycle on opening again. Normally, it is onPause->onResume but now it is onPause->onCreate.
You don't ever really want to close another application, due to Android activity lifecycle.
There's no benefit, and always detriment to closing another app if it's not yours, and very little benefit to closing your own.
http://developer.android.com/reference/android/app/Activity.html#ActivityLifecycle
If you know for certain that you'll never, ever need a root activity and its children (an "app"), you can stop it to free memory (it doesn't free that much), but if you do the user may restart it while it's still in cache, stopped, which can cause problems if the stopped state is restored. So this is a bad practice.