android – 检查应用程序是否在后台

前端之家收集整理的这篇文章主要介绍了android – 检查应用程序是否在后台前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我实际上正在使用此代码来检查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;
}

并且在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;
    }
});

我不知道令人兴奋的原因,但可能是因为处理程序中的差异线程我得到了正确的值

原文链接:https://www.f2er.com/android/315605.html

猜你在找的Android相关文章