我正在开发一个Android应用程序,它在后台运行一个服务,只有当用户在主屏幕上运行时才会运行。我遵循了这个类似的answer,但总是需要点击这个方法来得到答案。我使用以下代码。
@Override
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
super.onStart(intent, startId);
task = new TimerTask() {
@Override
public void run() {
detect();
}
};
Timer timer = new Timer();
timer.schedule(task, 0, 1000);
}
void detect(){
ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
taskInfo = am.getRunningTasks(1);
ComponentName currentTask = taskInfo.get(0).topActivity;
final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
mainIntent.addCategory(Intent.CATEGORY_HOME);
mPackageManager = getPackageManager();
List<ResolveInfo> appList = mPackageManager.queryIntentActivities(mainIntent, 0);
for(int i = 0; i < appList.size(); i++) {
ResolveInfo apl = appList.get(i);
if(currentTask.getPackageName().equals(apl.activityInfo.packageName)) {
Log.e(TAG, "ONHOMESCREEN");
}
}
}
BroadcastReceiver
是否有任何解决方案可以通过Intent
接收主屏幕是否在焦点上?
请帮助......