我如何检查,如果我暂停或退出应用程序为Android [英] How do I check if I am pausing or exiting the application for android

查看:108
本文介绍了我如何检查,如果我暂停或退出应用程序为Android的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在写为Android,我需要启动服务的时候我退出或暂停该应用程序的应用程序。我该怎么办?在我的应用程序,当我点击一个东西每一次,它会去到另一个活动,所以我不能把startservice里面那些活动的onPause。我该怎么办?

I am currently writing an app for android that i need to start the service when I exit or pause the application. What should i do? In my application, every time when I click a thing, it will go to another activity, so i cannot put the startservice to the onpause inside those activity. What should I do?

推荐答案

在活动不再是可见的,它会调用的onStop()。但是我们仍然不能肯定,如果应用程序被破坏的Andr​​oid操作系统在内部处理它。因此,尝试以下步骤找到,如果你的应用程序是在背景

When Activity is no longer visible, it calls onStop(). But still we can not be sure if app is destroyed as Android OS internally handles it. So try following steps to find if you app is in background:

  1. 使用获取正在运行的任务信息

  1. Get the running task info using

ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List<RunningTaskInfo> tasks = am.getRunningTasks(1);

  • 如果任务列表不为空,检查是否运行TAKS属于您的应用程序。如果属于,则返回true调用函数,在那里你可以开始你的服务;否则返回

     if (!tasks.isEmpty()) {
       ComponentName topActivity = tasks.get(0).topActivity;
      if (!topActivity.getPackageName().equals(context.getPackageName()))
      {
         return true;
      }
    

  • 编辑:这可能是有益的: <一个href="http://developer.android.com/reference/android/app/ActivityManager.html#getRunningAppProcesses" rel="nofollow">http://developer.android.com/reference/android/app/ActivityManager.html#getRunningAppProcesses

    Edit : This may be helpful : http://developer.android.com/reference/android/app/ActivityManager.html#getRunningAppProcesses

    这篇关于我如何检查,如果我暂停或退出应用程序为Android的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆