android


Android, how to get app on foreground


I'm trying to develop a service that whenever an user opens an app my service will identify it. I'm using the files: /proc/[pid]/cgroup,/proc/[pid]/cmdline,/proc/[pid]/oom_score,/proc/[pid]/oom_score_adj to check if it's an user app running on foreground. Actually it's working but when I try to open any game the service won't recognize it all the time. (The service only identify the files (oom_score) that has the lowest value).
Example: oom_score for "com.google.android.googlequicksearchbox:interactor" is 75, but for "com.king.candycrushsaga" will be >150, so it will never be detected by the code (as it follows).
Service code:
scheduler.scheduleAtFixedRate(new Runnable() {
#Override
public void run() {
s=appManager.getAppRunningForeground();
System.out.println(s);
}
},1,2,SECONDS);
Function that gets the app running:
private ReadWriteFile readWriteFile = new ReadWriteFile();
public String getAppRunningForeground(){
int pid;
File[] files = new File("/proc").listFiles();
int lowestOomScore = Integer.MAX_VALUE;
String foregroundProcess = null;
for (File file : files) {
if (!file.isDirectory() || (!file.getName().matches(("\\d+"))))
continue;
pid = Integer.parseInt(file.getName());
try {
String cgroup = readWriteFile.read(String.format("/proc/%d/cgroup", pid));
String[] lines = cgroup.split("\n");
if (lines.length != 2)
continue;
String cpuSubsystem = lines[0];
String cpuaccctSubsystem = lines[1];
if (!cpuaccctSubsystem.endsWith(Integer.toString(pid)) || cpuSubsystem.endsWith("bg_non_interactive"))
continue;
String cmdline = readWriteFile.read(String.format("/proc/%d/cmdline", pid));
if (cmdline.contains("com.android.systemui")||cmdline.contains("com.google.android.googlequicksearchbox:interactor")) {
continue;
}
int uid = Integer.parseInt(cpuaccctSubsystem.split(":")[2].split("/")[1].replace("uid_", ""));
if (uid > 1000 && uid <= 1038)//System process
continue;
File oomScoreAdj = new File(String.format("/proc/%d/oom_score_adj", pid));
if (oomScoreAdj.canRead()) {
int oomAdj = Integer.parseInt(readWriteFile.read(oomScoreAdj.getAbsolutePath()));
if (oomAdj != 0) {
continue;
}
}
int oomscore = Integer.parseInt(readWriteFile.read(String.format("/proc/%d/oom_score", pid)));
if (oomscore < lowestOomScore) {
lowestOomScore = oomscore;
foregroundProcess = cmdline.replaceAll("\\p{Cntrl}", "");
}
} catch (IOException e) {
e.printStackTrace();
}
}
return foregroundProcess;
}
Class that reads a file.
public class ReadWriteFile{
File file;
StringBuilder teste3 = new StringBuilder();
FileOutputStream outputStream;
public static String read(String path) throws IOException {
StringBuilder output = new StringBuilder();
BufferedReader reader = new BufferedReader(new FileReader(path));
output.append(reader.readLine());
for (String line = reader.readLine(); line != null; line = reader.readLine())
output.append('\n').append(line);
reader.close();
return output.toString();
}
}
P.S: getRunningTasks is deprecated, so please, don't suggest it.
You can use UsageStatsManager class added in android api 21. See this
question raised and answered by me.
The above answer will provide you an sorted applications ArrayList, required foreground application will the first one in the ArrayList on the index number 0.
Hope this will help.
This methods help you
void checkForegroundAppCompat()
{
ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
final List<ActivityManager.RunningTaskInfo> taskInfo = activityManager.getRunningTasks(1);
final ComponentName componentName = taskInfo.get(0).topActivity;
if(!getWhiteListedPackages().contains(componentName.getPackageName()) &&
SecurityStatusManager.isAppsBlockingEnabled(this))
{
int pid = android.os.Process.getUidForName(componentName.getPackageName());
// Kill blick APP here
GRLog.w("KILL Blacklist App Package: " + componentName.getPackageName() + " with pid: " + pid);
killApp(componentName.getPackageName(), pid);
}
}

Related Links

Not able to scan 2d barcode
Android Keyboard Add Key Programmatically
Android Layout disparity between API 16 and higher using radio groups
Splash-screen via Android Studio
How to implement offline google maps in Android?
ActionBar tabs misplaced in portrait using AppCompat theme
Android how to show DatePicker in Fragment?
When to delete file shared with external apps by using Intent.ACTION_SEND in Android
how to increase the height of the list view while animating from bottom to top android?
Android SimpleAdapter.ViewBinder is not working while getting data from XML Parsing
Android AudioRecord send over RTP/UDP
Android ListView is not scrolling
How to change the style progerssbar in SwipeRefreshLayout?
Mapbox get latitude and longitude from device precise location
network operation without asyncTask in Android
How to retrieve and play mp3 files from Parse.com

Categories

HOME
paraview
deep-learning
c++11
jmeter
ecmascript-6
twig
case
oracle-apex-5
grafana
ms-access-2016
newrelic
carousel
g++
automatic-ref-counting
gkturnbasedmatch
flash-player
glyphicons
esoteric-languages
easyphp
topology
backpack-for-laravel
inno-download-plugin
short-url
mount
opentk
bulletphysics
angular-translate
browser-sync
google-cast
volatile
jbutton
android-sugarorm
hreflang
sammy.js
gojs
vue-chartjs
jwplayer6
docfx
alphabetical
graphhopper
timing
connection-pool
verifiable-c
health-monitoring
urlsession
attributeerror
datacachefactory
parser-generator
pom.xml
jboss-4.2.x
datamaps
cronexpression
microstation
dotnetnuke-7
nikeplus-api
jquery-jscrollpane
cifilter
jclouds
query-by-example
bizagi
gcloud-ruby
pushbots
invoke-sqlcmd
httpruntime.cache
relativelayout
java-money
rate-limiting
amiga
nutiteq
teamcity-9.1
matlab-deployment
node-serialport
shopizer
nodelist
uncaught-typeerror
structuremap3
easyrtc
human-computer-interface
ignite-ui
lambda-architecture
build-script
live555
alternate
ray
light
isqlquery
scringo
nebula
node-blade
video-codecs
stacky
pstack
pyunit
mapping-by-code
luabind
role
mbeans
tmx
cloudfiles
office-2007
message-passing
scrollbars
murmurhash
complex-event-processing
cldc
linfu-dynamicproxy
entitykey
leader
mathematical-typesetting
pnrp

Resources

Mobile Apps Dev
Database Users
javascript
java
csharp
php
android
MS Developer
developer works
python
ios
c
html
jquery
RDBMS discuss
Cloud Virtualization
Database Dev&Adm
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App