我实际上正在使用此代码来检查onPause中的应用程序是否转到后台.
public static boolean isApplicationSentToBackground(final Context context) { ActivityManager am = (ActivityManager) context.getSystemService( Context.ACTIVITY_SERVICE ); List<RunningTaskInfo> tasks = am.getRunningTasks( 1 ); if (!tasks.isEmpty()) { ComponentName topActivity = tasks.get( 0 ).topActivity; String name = LockScreenActivity.class.getName(); String topAPN = topActivity.getPackageName(); String conAPN = context.getPackageName(); if (topActivity.getClassName().equals( name ) || !topActivity.getPackageName().equals( context.getPackageName() )) { return true; } } return false; }
到目前为止,这段代码在Android 4.4中运行良好.如果现在我检查topAPN并且它们是相同的(当应用程序在android< = 4.3上发送到后台时它们总是不相等). 你知道如何解决这个问题吗?有什么变化?
解决方法
我遇到了同样的问题.我为新版本解决了它.只需使用此代码
public static boolean isApplicationSentToBackground(final Context context) { ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); List<RunningTaskInfo> tasks = am.getRunningTasks(1); if (!tasks.isEmpty()) { ComponentName topActivity = tasks.get(0).topActivity; if (!topActivity.getPackageName().equals(context.getPackageName())) { return true; } } return false; }
@Override protected void onPause() { super.onPause(); handler.sendMessage(new Message()); } Handler handler=new Handler(new Handler.Callback() { @Override public boolean handleMessage(Message msg) { if (DeviceManager.isApplicationSentToBackground(getApplicationContext())) { paused = true; } return false; } });
我不知道令人兴奋的原因,但可能是因为处理程序中的差异线程我得到了正确的值