我在打开另一个已安装的应用时试图打开锁定活动。它的工作正常。锁定活动确实打开,但在另一个应用程序启动后打开。那么如何在另一个应用程序启动之前打开锁定活动?如果有人有解决方案,请帮助我。通过搜索我搜索get foreground task in android 5.0 +
的代码public void onReceive(Context context, Intent intent) {
DatabaseHelper databaseHelper = new DatabaseHelper(context.getApplicationContext());
try {
arrayList.clear();
Cursor cursor = databaseHelper.getAll();
if (cursor != null) {
if (cursor.moveToFirst()) {
arrayList.add(cursor.getString(2));
}
while (cursor.moveToNext()) ;
}
if (arrayList.size() == 0) {
activity = this.context.getPackageName().toString();
} else {
activity = arrayList.get(0).toString();
}
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { //For versions less than lollipop
ActivityManager am = ((ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE));
List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(5);
top = taskInfo.get(0).topActivity.getPackageName();
Log.v(TAG, "top from Receiver app = " + top);
for (ActivityManager.RunningTaskInfo info : taskInfo) {
if (info.topActivity.getPackageName().equalsIgnoreCase(activity)) {
intent = new Intent(context.getApplicationContext(), Lock_Screen.class);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
}
} else { //For versions Lollipop and above
List<AndroidAppProcess> processes = ProcessManager.getRunningForegroundApps(context.getApplicationContext());
Collections.sort(processes, new ProcessManager.ProcessComparator());
for (int i = 0; i <= processes.size() - 1; i++) {
if (!processes.get(i).name.isEmpty()) {
top = processes.get(i).name;
Log.e(TAG, "top from Receiver app=" + top);
if (processes.get(i).name.equalsIgnoreCase(activity)) {
intent = new Intent(context.getApplicationContext(), Lock_Screen.class);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
}
if (processes.get(i).name.equalsIgnoreCase("com.google.android.youtube")) { //always the package name above/below this package is the top app
if ((i + 1) <= processes.size() - 1) { //If processes.get(i+1) available, then that app is the top app
top = processes.get(i + 1).name;
} else if (i != 0) { //If the last package name is "com.google.android.gms" then the package name above this is the top app
top = processes.get(i - 1).name;
} else {
if (i == processes.size() - 1) { //If only one package name available
top = processes.get(i).name;
}
}
Log.v(TAG, "top app from Receiver = " + top);
}
}
}
// context.startService(new Intent(context.getApplicationContext(), Service_1.class));
databaseHelper.close();
}catch (Exception e){
e.getMessage();
e.getLocalizedMessage();
}
}