在 Android 中,要获取当前屏幕显示的 Activity,可以使用以下几种方法:
方法一:使用 ActivityManager 获取当前运行的任务信息
这是一个常见的方法,尽管从 Android 5.0 (API 21) 开始,有些方法变得不太可靠或受限制。
import android.app.ActivityManager;
import android.content.Context;
import android.os.Build;
public class ActivityUtils {
public static String getCurrentActivity(Context context) {
ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
if (activityManager != null) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
List<ActivityManager.AppTask> tasks = activityManager.getAppTasks();
if (tasks != null && !tasks.isEmpty()) {
ActivityManager.AppTask task = tasks.get(0);
ActivityManager.RecentTaskInfo taskInfo = task.getTaskInfo();
if (taskInfo != null && taskInfo.topActivity != null) {
return taskInfo.topActivity.getClassName();
}
}
} else {
List<ActivityManager.RunningTaskInfo> tasks = activityManager.getRunningTasks(1);
if (tasks != null && !tasks.isEmpty()) {
ActivityManager.RunningTaskInfo taskInfo = tasks.get(0);
if (taskInfo != null && taskInfo.topActivity != null) {
return taskInfo.topActivity.getClassName();
}
}
}
}
return null;
}
}
在你的 Activity 或其他组件中调用 getCurrentActivity
方法来获取当前显示的 Activity 名称。
2.杀掉当前运行的的那个app进程
/*** 杀掉 QQ 音乐的进程*/ public static void killQQMusicProcess(String packageName, Context context) {android.util.Log.d(TAG, "killQQMusicProcess");try {android.util.Log.d(TAG, " realy kill app: " + packageName);Process process = Runtime.getRuntime().exec("am force-stop " + packageName);process.waitFor();ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);List<ActivityManager.RunningAppProcessInfo> runningAppProcesses = activityManager.getRunningAppProcesses();for (ActivityManager.RunningAppProcessInfo processInfo : runningAppProcesses) {if (processInfo.processName.equals(packageName)) {android.util.Log.d(TAG, "Killing process: " + processInfo.pid);android.os.Process.killProcess(processInfo.pid);}}} catch (Exception e) {android.util.Log.e(TAG, "Error killing app: " + packageName, e);} }使用的地方调用: 需要杀进程的包名:BAAPP_QQMUSIC_PACKNAME =“con.android.tenxunAA” ActivityUtils.killQQMusicProcess(APP_QQMUSIC_PACKNAME, BlueConnectModeActivity.this);