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

android – 检查应用程序是否在后台,第1张

概述我实际上正在使用此代码来检查onPause中的应用程序是否转到后台. public static boolean isApplicationSentToBackground(final Context context) { ActivityManager am = (ActivityManager) context.getSystemService( Context.ACTIVITY_SE 我实际上正在使用此代码来检查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方法中以这种方式调用此函数

@OverrIDeprotected 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;    }});

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

总结

以上是内存溢出为你收集整理的android – 检查应用程序是否在后台全部内容,希望文章能够帮你解决android – 检查应用程序是否在后台所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/web/1136134.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-30
下一篇2022-05-30

发表评论

登录后才能评论

评论列表(0条)

    保存