一、使用广播更新悬浮窗布局
转自weixin_41476562 的 [安卓]!新人首贴!安卓开发实现在任何Activity下更新悬浮窗内容,感谢!
二、获取当前 Activity 的包名和类名
1、贴一个在用的工具类,适用5.0+,包括:
- 获取所有桌面应用
- 获取最近2秒内开始运行在界面上的程序包名
- 判断当前应用是否是后台运行
- 获取屏幕宽高
- 获取顶层的activity的包名
- 判断当前是否打开特定的软件
public class AppUtil {
/**
* 获取所有桌面应用
*
* @param context
* @return
*/
public static List<String> getHomeList(Context context) {
List<String> list = new ArrayList<String>();
PackageManager packageManager = context.getPackageManager();
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
List<ResolveInfo> resolveInfoList = packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
for (ResolveInfo resolveInfo : resolveInfoList) {
list.add(resolveInfo.activityInfo.packageName);
}
Log.i("homeList", list.toString());
return list;
}
/**
* 获取最近2秒内开始运行在界面上的程序包名
* 若最近2秒一直停留在某一界面,则返回null
*
* @param context
* @return
*/
public static String getLatestPackage(Context context) {
ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
String packname = null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//5.0之后getRunningTasks废弃,引入usage
//<uses-permission android:name="android.permission.PACKAGE_USAGE_STATS" tools:ignore="ProtectedPermissions" />
UsageStatsManager usageStatsManager = (UsageStatsManager) context.getSystemService(Context.USAGE_STATS_SERVICE);
long currentTime = System.currentTimeMillis();
List<UsageStats> usageStatsList = usageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_BEST, currentTime - 2000, currentTime);
if (usageStatsList != null || usageStatsList.isEmpty()) {
SortedMap<Long, UsageStats> usageStatsSortedMap = new TreeMap<Long, UsageStats>();
for (UsageStats usageStats : usageStatsList) {
usageStatsSortedMap.put(usageStats.getLastTimeUsed(), usageStats);
}
if (!usageStatsSortedMap.isEmpty()) {
packname = usageStatsSortedMap.get(usageStatsSortedMap.lastKey()).getPackageName();
}
}
} else {
//5.0之前可直接使用getRunningTasks
//<uses-permission android:name="android.permission.GET_TASKS"/>
List<ActivityManager.RunningTaskInfo> runningTaskInfoList = activityManager.getRunningTasks(1);
packname = runningTaskInfoList.get(0).topActivity.getPackageName();
}
Log.i("latest", packname == null ? "null" : packname);
return packname;
}
/**
* 判断当前应用是否是后台运行
*
* @param context
* @return
*/
public static boolean isBackground(Context context) {
ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
String packname = null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//5.0之后getRunningTasks废弃
//当前程序是否前台运行
//详见ActivityManager.START_TASK_TO_FRONT(hide),前台任务
int START_TASK_TO_FRONT = 2;
Field field = null;
try {
field = ActivityManager.RunningAppProcessInfo.class.getField("processState");
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
List<ActivityManager.RunningAppProcessInfo> runningAppProcessInfoList = activityManager.getRunningAppProcesses();
for (ActivityManager.RunningAppProcessInfo runningAppProcessInfo : runningAppProcessInfoList) {
if (runningAppProcessInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
//如果当前是运行在前台的UI
try {
Integer processState = field.getInt(runningAppProcessInfo);
if (START_TASK_TO_FRONT == processState) {
packname = runningAppProcessInfo.processName;
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
} else {
//5.0之前可直接使用getRunningTasks
//<uses-permission android:name="android.permission.GET_TASKS"/>
List<ActivityManager.RunningTaskInfo> runningTaskInfoList = activityManager.getRunningTasks(1);
packname = runningTaskInfoList.get(0).topActivity.getPackageName();
}
Log.i("packname", packname == null ? "null" : packname);
return !context.getPackageName().equals(packname);
}
/**
* 获取屏幕宽高
*
* @param context
* @return
*/
public static Point getScreen(Context context) {
Point point = new Point();
WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
windowManager.getDefaultDisplay().getSize(point);
return point;
}
/**
* 低、高版本:获取顶层的activity的包名
*
* @return
*/
public static String getPackageName(Context context) {
String topPackageName = "";
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
UsageStatsManager mUsageStatsManager = (UsageStatsManager) context.getSystemService(Context.USAGE_STATS_SERVICE);
long time = System.currentTimeMillis();
//time - 1000 * 1000, time 开始时间和结束时间的设置,在这个时间范围内 获取栈顶Activity 有效
List<UsageStats> stats = mUsageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, time - 1000 * 1000, time);
// Sort the stats by the last time used
if (stats != null) {
SortedMap<Long, UsageStats> mySortedMap = new TreeMap<Long, UsageStats>();
for (UsageStats usageStats : stats) {
mySortedMap.put(usageStats.getLastTimeUsed(), usageStats);
}
if (mySortedMap != null && !mySortedMap.isEmpty()) {
topPackageName = mySortedMap.get(mySortedMap.lastKey()).getPackageName();
Log.e("TopPackage Name", topPackageName);
}
}
} else {
ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
ComponentName topActivity = activityManager.getRunningTasks(1).get(0).topActivity;
topPackageName = topActivity.getPackageName();
}
return topPackageName;
}
/**
* 判断当前是否打开特定的软件
*/
public static boolean isWps(Context context) {
String topApp = getPackageName(context);
if (topApp.contains("wps")) {
return true;
} else {
return false;
}
}
6.0+需要在AndroidManifest.xml里添加权限:
<!--有权查看使用情况的应用-->
<uses-permission android:name="android.permission.PACKAGE_USAGE_STATS" tools:ignore="ProtectedPermissions" />
动态获取权限:
if (!checkUsagePermission(this)) {
startActivity(new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS));
}
/**
* 是否有权查看APP使用情况
* true 有权限
* false 无权限
*
* @param context
* @return
*/
public static boolean checkUsagePermission(Context context) {
AppOpsManager appOpsManager = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
int mode = appOpsManager.checkOpNoThrow(AppOpsManager.OPSTR_GET_USAGE_STATS, android.os.Process.myUid(), context.getPackageName());
return mode == AppOpsManager.MODE_ALLOWED;
}
2、 转自mafanwei 的 安卓获取当前的应用包名和应用类Activity名,适用于5.0+,感谢!