我实际上是在使用此代码来检查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
和conAPN
它们是相等的(当应用程序在android&lt; = 4.3上发送到后台时它们总是不相等的。)
你知道如何解决这个问题吗?有什么变化吗?
答案 0 :(得分:5)
我遇到了同样的问题。我为新版本解决了这个问题。只需使用此代码
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;
}
在onPause方法中以这种方式调用此函数
@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;
}
});
我不知道激动的原因但可能是因为处理程序中的差异线程我得到了正确的值
答案 1 :(得分:0)
此代码适用于android 4.4我在onStop中声明使用此方法,它是:
//应用程序代码返回
@Override
protected void onStop() {
super.onStop();
if (AppConstants.isAppSentToBackground(getApplicationContext())) {
// Do what ever you want after app close simply Close session
}
}
// Method to Check Our app is running or Not
public static boolean isAppSentToBackground(final Context context) {
try {
ActivityManager am = (ActivityManager) context
.getSystemService(Context.ACTIVITY_SERVICE);
// The first in the list of RunningTasks is always the foreground
// task.
RunningTaskInfo foregroundTaskInfo = am.getRunningTasks(1).get(0);
String foregroundTaskPackageName = foregroundTaskInfo.topActivity
.getPackageName();// get the top fore ground activity
PackageManager pm = context.getPackageManager();
PackageInfo foregroundAppPackageInfo = pm.getPackageInfo(
foregroundTaskPackageName, 0);
String foregroundTaskAppName = foregroundAppPackageInfo.applicationInfo
.loadLabel(pm).toString();
// Log.e("", foregroundTaskAppName +"----------"+
// foregroundTaskPackageName);
if (!foregroundTaskAppName.equals("Your App name")) {
return true;
}
} catch (Exception e) {
Log.e("isAppSentToBackground", "" + e);
}
return false;
}