好的,首先我读了很多问题和文章,但对我来说却不是这项工作
解决方案对我不起作用-
Android, Detect when other apps are launched
Detect when user launches a new application on an Android device
How to detect when the user launches another app? (Android)
要做什么-在用户启动应用程序(如applock)时检查并打开“特定锁”活动
问题-
我使用 activityManager 并获得应用程序的程序包名称,但它仅在我离开应用程序时显示在我的应用程序上,显示启动器的程序包名称,如果我打开另一个应用程序,它仍显示启动器包名称,所以我尝试检查它是否为启动器,然后显示toast,但不起作用
,当我使用UsageStatsManager检测启动应用程序包名称时,它始终显示空白吐司。
这是我的代码
public class LockService extends Service {
public final IBinder mBinder = new MyBinder();
public Context context;
private String current_app = null;
public Handler mhandler;
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
mhandler = new Handler();
context = LockService.this;
startRepeatProcess();
return Service.START_STICKY;
}
Runnable mStatusChecker = new Runnable() {
@Override
public void run() {
try {
try {
context = LockService.this;
current_app = getRecentApps(context);
if(!current_app.contains("launcher")){
Toast.makeText(context,current_app,Toast.LENGTH_SHORT).show();
}
}catch (Exception e){
e.printStackTrace();
}
} finally {
mhandler.postDelayed(mStatusChecker, 700);
}
}
};
private void startRepeatProcess() {
mStatusChecker.run();
}
public String getRecentApps(Context context) {
String topPackageName = null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
UsageStatsManager mUsageStatsManager = (UsageStatsManager) context.getSystemService(Context.USAGE_STATS_SERVICE);
long time = System.currentTimeMillis();
List<UsageStats> stats = mUsageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, time - 1000 * 10, time);
if (stats != null) {
SortedMap<Long, UsageStats> mySortedMap = new TreeMap<Long, UsageStats>();
for (UsageStats usageStats : stats) {
mySortedMap.put(usageStats.getLastTimeUsed(), usageStats);
}
if (!mySortedMap.isEmpty()) {
topPackageName = mySortedMap.get(mySortedMap.lastKey()).getPackageName();
}
}
} else {
ActivityManager am = (ActivityManager) context.getSystemService(context.ACTIVITY_SERVICE);
List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);
ComponentName componentInfo = taskInfo.get(0).topActivity;
topPackageName = componentInfo.getPackageName();
}
return topPackageName;
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
Toast.makeText(getApplicationContext(), "Started", Toast.LENGTH_SHORT).show();
return mBinder;
}
public class MyBinder extends Binder {
LockService getService() {
return LockService.this;
}
}
}