我正在创建一个应用储物柜。我想检测用户何时启动另一个应用程序,以便可以向用户显示我的锁定屏幕。现在,我可以针对特定操作(即当用户打开屏幕时)打开锁定屏幕。当屏幕状态更改时,我的服务将运行并检查前台应用程序。如果该应用程序在我已阻止的应用程序列表中,则会出现锁定屏幕。但是我想在用户每次启动另一个应用程序时启动服务。以下是我的BroadcastReciever类的代码
public void onReceive(Context context, Intent intent) {
if (Intent.ACTION_SCREEN_ON.equals(intent.getAction()))
{
Intent service = new Intent(context, BackgroundService.class);
context.startService(service);
Intent service1 = new Intent(context, BackgroundService.class);
context.stopService(service1);
}
答案 0 :(得分:1)
您无法检测到某个应用程序是否在特定时间启动,但是您肯定可以确定是否有其他应用程序在前台。
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;
}
要检测应用程序是否仅位于RAM中(位于前台还是后台),请使用以下命令:
ActivityManager am =(ActivityManager)getSystemService(Context.ACTIVITY_SERVICE);
List
for (int i = 0; i < runningAppProcessInfo.size(); i++) {
if(runningAppProcessInfo.get(i).processName.equals("com.the.app.you.are.looking.for")
{
// Do you stuff
}
}
如果没有,您可以考虑启动BG检查并尝试查找。前景中的应用增加了,这意味着将启动一个新应用。
选项2:
我认为我们可以使用logcat并分析其输出。
在所有类似程序中,我均已获得此权限:
android.permission.READ_LOGS
这意味着他们所有人都在使用它,但是似乎程序启动了,然后我们的程序(应用保护程序)就会启动并显示出来。
使用以下代码:
try
{
Process mLogcatProc = null;
BufferedReader reader = null;
mLogcatProc = Runtime.getRuntime().exec(new String[]{"logcat", "-d"});
reader = new BufferedReader(new
InputStreamReader(mLogcatProc.getInputStream()));
String line;
final StringBuilder log = new StringBuilder();
String separator = System.getProperty("line.separator");
while ((line = reader.readLine()) != null)
{
log.append(line);
log.append(separator);
}
String w = log.toString();
Toast.makeText(getApplicationContext(),w, Toast.LENGTH_LONG).show();
}
catch (Exception e)
{
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
注意:-出于安全原因,第三部分应用程序无法使用systen权限来读取日志,而Android 4.1却如此 在这里阅读更多 https://commonsware.com/blog/2012/07/12/read-logs-regression.html.Option 1是您最好的选择。