How some apps still can get current apps processes and kill them? - android

Background
In the past, I've found the next method of killing an app's background processes, given its package name:
public static boolean killApp(final Context context, final String packageName) {
final ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
final List<ActivityManager.RunningAppProcessInfo> pids = am.getRunningAppProcesses();
for (int i = 0; i < pids.size(); i++) {
final ActivityManager.RunningAppProcessInfo info = pids.get(i);
if (info.processName.equals(packageName)) {
android.os.Process.killProcess(info.pid);
if (new File("/system/bin/kill").exists()) {
InputStream inputStream = null;
try {
inputStream = Runtime.getRuntime().exec("kill -9 " + info.pid).getInputStream();
final byte[] buffer = new byte[100];
inputStream.read(buffer);
} catch (final IOException e) {
}
StreamsUtil.closeStream(inputStream);
}
am.killBackgroundProcesses(packageName);
return true;
}
}
am.killBackgroundProcesses(packageName);
return false;
}
The problem
Ever since a specific Android version (5.1), the function to get the list of running processes only returns the current app's processes, so it's quite useless to use it.
What I've found
Most apps on the Play Store indeed fail to show a list of processes, and instead, show just the current app's process or a list of services at most.
It seems that some apps still manage to show background apps processes and even be able to kill them. As an example, I've found AVG's app that's capable of doing so, here .
Before they can do it, they tell the user to enable the usage stats settings for the app, which I remember of using for checking general information of apps launch time.
Another app that succeeded killing background processes, yet without any user confirmation , is "fast task killer". It also shows a toast of all processes being killed. I could be wrong, but it seems that it's always the same number of tasks.
I also think there is a relatively easy way to get the list of processes using the "ps" function, but only if the device is rooted (otherwise it will return just the current app's processes).
There was a temporary solution with a library, found here (published here), but this doesn't seem to work on Android 7.1.2 , and most probably on previous versions.
The question
How do apps get the list of apps that have background processes, and how do they kill them?
Is it possible to do so without using the UsageStatsManager class ?

Related

Stop background apps permanently Android

I am curious how apps like Task Managers & a specific app named Purify are able to permanently stop(force stop) background apps without requiring root permissions.
I searched & found a few ways but they were not efficient enough to stop all apps.
First method I found was to use KILLBACKGROUNDPROCESSES function but it was not able to kill all the background apps.
Secondly, I read about the SU FORCE STOP method but it requires root.
How are the apps able to do it without root?
Some Android applications can close other processes that are currently running in the background, not all process can be terminated. Some process even if terminated are restarted immediately. (You can try to close some from the 'application manager' and see for yourself).
You could try the following code that i compiled, it allows you to specify which processes that you may not want to kill.
// List of packages not to kill
List<String> reservedPackages = new ArrayList<String>();
reservedPackages.add("system");
reservedPackages.add("com.android.launcher2");
reservedPackages.add("com.android.inputmethod.latin");
reservedPackages.add("com.android.phone");
reservedPackages.add("com.android.wallpaper");
reservedPackages.add("com.google.process.gapps");
reservedPackages.add("android.process.acore");
reservedPackages.add("android.process.media");
//kill all except that in the list above
int processKillCounter = 0;
ActivityManager am = (ActivityManager) this.getBaseContext().getSystemService(Activity.ACTIVITY_SERVICE);
List<ActivityManager.RunningAppProcessInfo> listeProcessus = am.getRunningAppProcesses();
for(ActivityManager.RunningAppProcessInfo processus : listeProcessus) {
String packageName = processus.processName.split(":")[0];
if (!this.getBaseContext().getPackageName().equals(packageName) && !reservedPackages.contains(packageName)) {
am.restartPackage(packageName);
processKillCounter++;
}
}
mi = new ActivityManager.MemoryInfo();
activityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
activityManager.getMemoryInfo(mi);
long afterBoostMemory = mi.availMem / 1048576L;
long boostedMemory = afterBoostMemory - availableMegs;
//Percentage can be calculated for API 16+
long percentAvail = mi.availMem / mi.totalMem;
Toast.makeText(this,"Phone Boosted, "+boostedMemory + " MB freed", Toast.LENGTH_LONG).show();

Kill another Background Application in android

Problem: I want to kill a background application process.
We call the below methods inside a background thread/services and it's not working.
We have tried a few methods available on net but not succeeding to kill the background process/application.
My Device has a root permisision already.
Code here
1st Method:
int value = findPIDbyPackageName("com.google.android.youtube");
android.os.Process.sendSignal(value, 9);
2nd Method:
ActivityManager activityManager = (ActivityManager)this.getSystemService(ACTIVITY_SERVICE);
activityManager.killBackgroundProcesses("com.google.android.youtube");
3rd Method:
ActivityManager activityManager = (ActivityManager) this.getSystemService(ACTIVITY_SERVICE);
activityManager.restartPackage("com.google.android.youtube");
4th Method :
android.os.Process.killProcess(pid);
5th Method : `
List<ApplicationInfo> packages;
PackageManager pm;
pm = getPackageManager();
packages = pm.getInstalledApplications(0);
ActivityManager mActivityManager = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);
for (ApplicationInfo packageInfo : packages) {
if((packageInfo.flags & ApplicationInfo.FLAG_SYSTEM)==1)continue;
if(packageInfo.packageName.equals("mypackage")) continue; // here my package defines your application package entered in manifest
else if(packageInfo.packageName.equals("third Party application Package Name")) // if you dont have this package name then prefer playstore url of this app to get packagename
mActivityManager.killBackgroundProcesses(packageInfo.packageName);
}
6th
We launched a third party app like youtube, Subway surf from our own android app.
We are using startActivityForResultmethod for launching the app.
launchApp("com.imangi.templerun");
protected void launchApp(String packageName) {
mIntent = getPackageManager().getLaunchIntentForPackage(packageName);
if (mIntent != null) {
try {
startActivityForResult(mIntent, 101);
} catch (ActivityNotFoundException err) {
Toast t = Toast.makeText(this, "App not found", Toast.LENGTH_SHORT); t.show();
}
}
}
To close the application, the method finsihActivity(ResposneCode) is available.
But we're not able to use it in service.
You are not allowed to kill processes which don't belong to your app. The system will decide when to kill and what to kill when necessary.
App intervention is just to tell the system a message, Please help me to kill this process, blah blah..., that's all.
Process.killProcess() should work, this is your method number 4.
Read carefully what it says.
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.
Under root permission you should be able to remove the kernel restrictions, unfortunately I do not know how to do this, I suggest you to search for native solution for that, may be some C codes, there are plenty of them in the net.
Also in your method 1 you been trying to send SIGNAL_KILL, try sending SIGNAL_QUIT

Listener for Phone Events and Voice command

My app uses a microphone(AudioRecord) in a background mode,How to make the listener for phone events and voice commands (like google voice). It is necessary for me to release a microphone(AudioRecord) for use.
I found a solution to phone events: http://www.botskool.com/geeks/how-listen-phone-events-android.
to use: TelephonyManager , PhoneStateListener.
But not to voice commands. Help pls.
There is no specific way you can do this (unfortunately) and it will only be the application that attempts to use the mic resource that will get an error.
What you can do is monitor what the user is doing in the background and react accordingly. Here is the code to check if Google Now has become the foreground application:
public static boolean googleNowForeground(final Context ctx) {
final ActivityManager activityManager = (ActivityManager) ctx.getSystemService(Context.ACTIVITY_SERVICE);
if (activityManager.getRunningTasks(1).get(0) != null) {
final PackageManager pm = ctx.getPackageManager();
try {
final PackageInfo foregroundAppPackageInfo = pm.getPackageInfo(
activityManager.getRunningTasks(1).get(0).topActivity.getPackageName(), 0);
if (foregroundAppPackageInfo != null) {
if (foregroundAppPackageInfo.packageName.matches(Constants.GOOGLE_NOW_PACKAGE_NAME)) {
return true;
}
}
} catch (NameNotFoundException e) {
e.printStackTrace();
}
}
return false;
}
This is the least 'expensive' way I've found to perform such actions, but the method above is not guaranteed to be called in future OS versions, not to mention having to hard-code the package names you are concerned with....
The 'expense' of monitoring for foreground applications that you know will conflict with your application may be somewhat minimal in comparison to permanently recording audio, but you should code your implementation wisely to minimise the monitor within certain device condition parameters.
I've investigated other methods to monitor intent broadcasts that are associated with mic resources, but they've been less successful than the above.
Requesting that the user create an 'exclude list' for the conflicting applications will allow you to dynamically monitor if they become the foreground application and react accordingly.
Hope that helps....

How can I get a list of CACHED processes?

I am trying to get a list of cached processes. I already know how to get running processes and services by their class name, but how can I get a list of the Cached processes and services by their host name?
If you go under settings on your android device, and click "apps" then choose "running" if you press the menu button you can switch between running services or cached processes. I am trying to get a list of all cached processes by their class name.
You can check the source code in settings of android:
http://androidxref.com/4.2_r1/xref/packages/apps/Settings/src/com/android/settings/applications/RunningProcessesView.java
and check the various: mSetBackground in ActiveItem
all mSetBackground = true are cached processes
So I sort of got it, this is doing exactly what the settings view does.
StringBuilder temp = new StringBuilder();
for(RunningAppProcessInfo processInfo : am.getRunningAppProcesses()){
if(processInfo.importance == 400) {
temp.append(processInfo.processName);
temp.append("\n");
}
But its only returning the package name and not the full activity name.

How to detect when the user launches another app? (Android)

I'm trying to build an application where my application runs in the background and detects when the user launches another application so that I can control the flow from thereon.
To illustrate my query, I'd like to specify an example.
My application is running in the background (say as a Service), and the user has just clicked on application 'XYZ'. Is it possible for my app to detect that app 'XYZ' has been launched?
More than just detecting whether 'XYZ's Activity has come to the foreground,I want to detect whther 'XYZ' has been launched or not. Say someone launches 'Whatsapp Messenger', I want to know if my app can know that 'Whatsapp Messenger' has been launched.
EDIT : A lot of people think I'm trying to build malware, but I'm not. I'm trying to build an app for a high school project. I want a stat to see how often I use my camera as part of a psych project. :/
Thanks in advance,
Sumit.
Yes, You can find the which application is launched, by Tracking the Logcat. Just Track on ActivityManager tag with info -I log.
From adb shell Command is,
adb logcat ActivityManager:I *:S
From your application code,
logcat ActivityManager:I *:S
And in Logcat you can find a line something like,
I/ActivityManager( 585): Starting activity: Intent { action=android.intent.action...}
When any application will launched.
It is logcat output that shows that the message relates to priority level "I" and tag "ActivityManager":
Update:
Just add permission in your Application's manifest file,
android.permission.READ_LOGS
I guess you should have a look at "app protector" applications in the Google Play. They detect that user launched another application. That is done by reading system logs. Try opening LogCat and reading logs after you launched any application on device. You'll be surprised.
And where should you go from there? I guess you should try aLogCat app. It's freen and open-source. That will help you to actually read logs.
All this is considered to be a security breach in Android by some developers, though.
I have made a service which can detect if other application launches. I have made it for dialer. similarly that can be replaced by any package name.
#Override
public int onStartCommand(Intent intent, int flags, int startId){
Toast.makeText(this,"Service Started", Toast.LENGTH_LONG).show();
final String str = "";
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
int phonelaunched = 0,phoneclosed =0;
int phonelaunches = 1;
#Override
public void run() {
ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningAppProcessInfo> runningAppProcessInfo = am.getRunningAppProcesses();
for ( ActivityManager.RunningAppProcessInfo appProcess: runningAppProcessInfo ) {
Log.d(appProcess.processName.toString(),"is running");
if (appProcess.processName.equals("com.android.dialer")) {
if ( appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND /*isForeground(getApplicationContext(),runningAppProcessInfo.get(i).processName)*/){
if (phonelaunched == 0 ){
phonelaunched = 1;
Log.d(str,"dude phone has been launched");
}
else if (phoneclosed == 1){
phonelaunches++;
phoneclosed = 0;
Log.d(String.valueOf(phonelaunches),"dude that was counter");
}
}
else {
phoneclosed = 1;
Log.d(str,"dude phone has been closed");
}
}
}
}
},2000,3000);
return START_STICKY;
}
Here I go through all the running tasks and check if it is our intended application. If so I check if the application is foreground and application is never launched using 'phonelaunched' variable. phoneclosed is used when intended application is in background and variable is set accordingly.
All this is implemented in Service class
In my book, by the way you posed the question, that sounds like hi-jacking an app in a certain way for your service to control, bordering on malware jinx. But it will not work in Android - plain and simple due to the permissions of each application is different. Thereby, each app are isolated from one another. So to answer your question bluntly, its No.
As the other answer suggested - you can monitor the logcat but.. then again... why?

Categories

Resources