Android Java Get All Backround Running Apps Or Services - java

My Goal is very simple. I am Developing An App killer(Hibernator).
I Want to make same as "Hibernator.apk", it's Package name is "com.tafayor.hibernator".
What it does that It iterate All background apps or Services. and then It Hibernate All one by One.
It also ask Accessibility permissions once pr day.
My Requirements are below.
Get all background running apps or Services.(not my App).
Or A funtion to detect an app which is running in background (not my app nor in recent apps) by package name.
Completely Suspend (hibernate) app by package name.
I have tried.
ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningAppProcessInfo> runningAppProcessInfo = am.getRunningAppProcesses();
for (int i = 0; i < runningAppProcessInfo.size(); i++) {
if(runningAppProcessInfo.get(i).processName.equals("com.the.app.you.are.looking.for")) {
// Do your stuff here.
}
}
And
public static boolean isForeground(Context ctx, String myPackage){
ActivityManager manager = (ActivityManager) ctx.getSystemService(ACTIVITY_SERVICE);
List< ActivityManager.RunningTaskInfo > runningTaskInfo = manager.getRunningTasks(1);
ComponentName componentInfo = runningTaskInfo.get(0).topActivity;
if(componentInfo.getPackageName().equals(myPackage)) {
return true;
}
return false;
}
But it Shows only my app.

Use UsageStatsManager instead ActivityManager or AndroidProcesses.getRunningAppProcesses() . Add <uses-permission android:name="android.permission.PACKAGE_USAGE_STATS"/> in your Manifest file.
Also give usage access permission to your app . Hope this answer give you a clue , use your desired logic.

Related

How can i disable any android app such that it cannot be opened until i change/press some button in app?

I am trying to build a parental control app. So now i want to disable or lock app (like Whatsapp, Facebook, etc). I have tried using PackageManager.setComponentEnabledSetting(). But it is throwing java.lang.SercurityException.
So how can I make a parental control app such that I can disable any app I want without root.
my code is
pm.setComponentEnabledSetting(new ComponentName(temp.activityInfo.packageName,
temp.activityInfo.name+".class"),
PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
PackageManager.DONT_KILL_APP);
my error was this
java.lang.SecurityException: Permission Denial: attempt to change component state from pid=11537, uid=10067, package uid=10029
You must add below permissions to manifest.
<uses-permission android:name="android.permission.WRITE_SETTINGS"/>
<uses-permission android:name="android.permission.WRITE_SECURE_SETTINGS"/>
but , these permissions are for System apps and you can not use. :(
You can not write a app to lock or close another app.this is a policy in Google.
for lock a app you must check running apps repeatedly, if specific app is open,then show a activity over that.
while(!Thread.currentThread().isInterrupted())
{
String topActivity = getFrontApp();
if(topActivity.isEmpty())
{
threadSleep(500);
continue;
}
if(topActivity.equals("lockApp"))
{
showLockActivity();
}
threadSleep(500);
}
// for Api21+ need permission
public static String getFrontApp()
{
if (Build.VERSION.SDK_INT >= 21)
{
UsageStatsManager usageManager = SystemMaster.getUsageStatsManager();
long now = System.currentTimeMillis();
List<UsageStats> localList = usageManager.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, now - 900_000L, now);
String str = "";
if (localList != null)
{
SortedMap<Long,UsageStats> mySortedMap = new TreeMap<>();
for(UsageStats usageStats : localList)
mySortedMap.put(usageStats.getLastTimeUsed(), usageStats);
if(!mySortedMap.isEmpty())
str = mySortedMap.get(mySortedMap.lastKey()).getPackageName();
}
return str;
}
else
{
ActivityManager am = (ActivityManager) getApplication().getSystemService(Context.ACTIVITY_SERVICE);
return am.getRunningTasks(1).get(0).topActivity.getPackageName();
}
above code is very simple , for real app must write more.

how to stop my VPN app from being running if a specific app is installed

I have an android VPN app running on OpenVPN core, so I want to check if a specific app is installed, on connecting the app, it will stop and request for such app to be uninstalled before it works.
I have seen such on an app using JSON for all the app id blacklisted and I really don't know to go about it on my own app.
here is the JSON image file:
Blacklist.json
thank you.
You need to figure out what is the right package name of any installed application on your device.
Getting Package Info:
private boolean isPackageInstalled(String packageName, PackageManager packageManager) {
try {
packageManager.getPackageInfo(packageName, 0);
return true;
} catch (PackageManager.NameNotFoundException e) {
return false;
}
}
Then you can check in here like,
PackageManager pm = context.getPackageManager();
boolean isInstalled = isPackageInstalled("com.somepackage.name", pm);
if(isInstalled) {
// NO VPN
}
else {
// start your service
}

How to know if a specific app comes to foreground?

Check if an app, for example, Instagram is started by user.
Note: My app is targeting lollipop and above versions in android
Yeah the only way you can do it is through the Accessibility Service. Look at this page to understand how to create it. https://developer.android.com/training/accessibility/service.html They will also need to enable the service via the services -> accessibility screen.
AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED you can probably interrogate the package in front to figure out if Instigram is on top.
You definitely don't want to use getRunningTasks since the function was modified in Android 5.0+
I figured out that I can do this by using usage access feature.
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
public static String getForegroundProcess(Context context) {
String topPackageName = null;
UsageStatsManager usage = (UsageStatsManager) context.getSystemService(Context.USAGE_STATS_SERVICE);
long time = System.currentTimeMillis();
List<UsageStats> stats = usage.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, time - 1000*1000, time);
if (stats != null) {
SortedMap<Long, UsageStats> runningTask = new TreeMap<Long,UsageStats>();
for (UsageStats usageStats : stats) {
runningTask.put(usageStats.getLastTimeUsed(), usageStats);
}
if (runningTask.isEmpty()) {
return null;
}
topPackageName = runningTask.get(runningTask.lastKey()).getPackageName();
}
if(topPackageName==null) {
Intent intent = new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS);
context.startActivity(intent);
}
return topPackageName;
}
Now continuously check if the desired app is in the foreground.
String fg=getForegroundProcess(getApplicationContext());
if(fg != null && fg.contains("com.instagram.android")){
//Instagram is in foreground
}else {
}
I continuously run the above code with a job service.Which is available for
lollipop and above.

Add android.permission.MANAGE_USB permission to existing system application

We have an application installed on a rooted device as a system application. The latter doesn't have the android.permission.MANAGE_USB and we want to add it to a newer version so that the permission is given to the user automatically. I have followed the post:
bypass android usb host permission confirmation dialog
More specifically, the answer marked as correct from the user d_d_t.
Why doesn't it work? I mean, I have taken this newer version, directly installed it as our original system application and it works perfectly! But when I update the existing version with no usb permission with the newer version it just doesn't work. The new one is just an update. Same certificate and all.
I'm at a loss. Any thoughts?
Our code below:
AndroidManifest.xml.
<uses-permission
android:name="android.permission.MANAGE_USB"
android:protectionLevel="signature" />
Java class.
try {
PackageManager pm = getApplicationContext().getPackageManager();
ApplicationInfo ai = pm.getApplicationInfo(getApplicationContext().getPackageName(), 0);
if (ai != null) {
UsbManager manager = (UsbManager) getApplicationContext().getSystemService(Context.USB_SERVICE);
IBinder b = ServiceManager.getService(Context.USB_SERVICE);
IUsbManager service = IUsbManager.Stub.asInterface(b);
HashMap<String, UsbDevice> deviceList = manager.getDeviceList();
Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();
while (deviceIterator.hasNext()) {
UsbDevice device = deviceIterator.next();
if (device.getVendorId() == 0x0403) {
service.grantDevicePermission(device, ai.uid);
service.setDevicePackage(device,getApplicationContext().getPackageName(), 0);
}
}
}
} catch (Exception e) {
Log.e("UsbReceiver", "exception " + e);
e.printStackTrace();
}

Check App is installed on device android code

I downloaded apk file from url(my server) and save it in sdcard. If user install it from sdcard, I want to know, whether is any notification that app is installed successfully or is app istalled in device. Is there any callback on installed app
try this code :
protected boolean isAppInstalled(String packageName) {
Intent mIntent = getPackageManager().getLaunchIntentForPackage(packageName);
if (mIntent != null) {
return true;
}
else {
return false;
}
}
to get the package name of the app easily : just search your app in the google play website , and then you will take the id parameter ( it is the package name of the app) . Example :
you will search on Youtube app on google play , and you will find it in this url :
https://play.google.com/store/apps/details?id=com.google.android.youtube&feature=search_result#?t=W251bGwsMSwxLDEsImNvbS5nb29nbGUuYW5kcm9pZC55b3V0dWJlIl0.
the package name is the id param, so it is : com.google.android.youtube
And then when you want to test , you will just have :
String packageName = "com.google.android.youtube";
boolean isYoutubeInstalled = isAppInstalled(packageName);
PLUS : if you want to get the list of all installed apps in you device , you can find your answer in this tutorial
final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
final List pkgAppsList = context.getPackageManager().queryIntentActivities( mainIntent, 0);
You'll get the list of all installed applications on Android.
Use this to check if an application is installed
PackageManager pm = context.getPackageManager();
List<ApplicationInfo> list = pm.getInstalledApplications(0);
for (int i = 0; i < list.size(); i++) {
if(list.get(i).packageName.equals("com.my package")){
//do what you want
}
}
In Youtube Player API, you can access YoutubeIntents class and use isYoutubeInstalled to verify if device has the Android app or not.

Categories