Android应用程序的开始和结束事件 [英] Android app start and end event

查看:69
本文介绍了Android应用程序的开始和结束事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个应用程序,该应用程序可以跟踪用户在应用程序上的活动(包括时间等),现在,如果用户已打开该应用程序,它将开始一个会话,直到该应用程序中的用户,他的会话将继续进行,他可以切换到多个活动.现在,与此同时,他切换到另一个应用程序时,应该停止他的会话记录并将其记录到文件中

I have an app which track user activity on app which include time etc, Now if user has opened the app, It will start an session and till user in this app , his session will continue, He can switch to multiple activity. Now meantime he switches to another app, His session logging should be stopped and written down to file

我尝试过的

我创建了一个基本活动, 在恢复事件中,如果计数器为零,则我开始会话并递增计数器,然后 停止事件发生时,我递减计数器,如果计数器为零,则我停止会话

I created one base activity and On resume event if counter is zero, I start session and increment counter and On stop event , i decrement counter and if counter is zero, I stop session

但这不会计算跟踪的实际问题,因为当用户切换到另一个应用程序时android不会停止活动.

But this will not calculate actual problem of tracking as android doesn't stop activity as user switch to another app.

那么有什么办法可以实现这一目标.

So is there any way to achieve such thing.

其他:

如果我们可以获取屏幕上是否有应用活动处于活动状态,以便可以将事件用于开始或结束会话.

If we can get whether app activity is active on screen so event can be used to start or end session.

推荐答案

我可以想到两种方法:

您可以创建一个服务,该服务在前台扫描当前应用程序,并查看它是否是您的活动.这是您可以使用的一些代码,我从另一个答案中获取了它:

You can create a service which scans for the current application on the foreground and see if it is your activity. Here is some code you can use, I took it from another answer:

有一种简单的方法可以从 ActivityManager服务.您可以请求最大数量的任务 在电话上运行,默认情况下,当前处于活动状态的任务是 首先返回.

There's an easy way of getting a list of running tasks from the ActivityManager service. You can request a maximum number of tasks running on the phone, and by default, the currently active task is returned first.

一旦有了,您可以通过请求获得ComponentName对象 您列表中的topActivity.

Once you have that you can get a ComponentName object by requesting the topActivity from your list.

这是一个例子.

ActivityManager am = (ActivityManager) this.getSystemService(ACTIVITY_SERVICE);

     // get the info from the currently running task
     List< ActivityManager.RunningTaskInfo > taskInfo = am.getRunningTasks(1); 

     Log.d("topActivity", "CURRENT Activity ::"
             + taskInfo.get(0).topActivity.getClassName());

     ComponentName componentInfo = taskInfo.get(0).topActivity;
   componentInfo.getPackageName();

您需要在清单上具有以下权限:

You will need the following permission on your manifest:

<uses-permission android:name="android.permission.GET_TASKS"/>

链接到答案: Android:如何获取当前的前台活动(通过服务)?

您可以每隔一秒钟或更短的时间调用一次,以检测您的应用程序是否仍处于活动状态.请注意,根据官方文档,它已被弃用,不建议用于这种用途:

You can call this every one second or less to detect if your app is still active. Please note that it is a deprecated and is not recommended for using for this kind of things, according to official documentation:

getRunningTasks()

getRunningTasks()

注意:此方法仅用于调试和演示任务 管理用户界面.永远不要将其用于核心逻辑 在一个应用程序中,例如决定基于不同的行为 关于此处找到的信息.不支持此类用途,并且会 将来可能会中断.例如,如果多个应用程序可以 同时积极运行,有关 为了控制流程的目的,此处数据的含义将是 不正确.

Note: this method is only intended for debugging and presenting task management user interfaces. This should never be used for core logic in an application, such as deciding between different behaviors based on the information found here. Such uses are not supported, and will likely break in the future. For example, if multiple applications can be actively running at the same time, assumptions made about the meaning of the data here for purposes of control flow will be incorrect.


选项2:

第二个选项是创建一个扩展了Application并带有标志的类,例如isAppRunning,根据您的应用程序是否在前台,它将为true或false:


Option 2:

The second option is to create a class that extends Application with a flag, for example isAppRunning, which will be true or false according if your application is on the foreground or not:

public class MyAppContext extends Application {

   public boolean isAppRunning = true;

   public void setIsAppRunning(boolean v){
      isAppRunning = v;
   }

   public boolean isAppRunning(){
      return isAppRunning;
   }

}

然后在您的AndroidManifest.xml上,您必须添加此类,以便在您的应用程序启动时使用该类.只需在应用程序标签下添加android:name=".MyAppContext":

Then on your AndroidManifest.xml you have to add this class so it will be used when your application starts. Just add android:name=".MyAppContext" under the application tag:

<application
        android:name=".MyAppContext"

现在,在您进行的每个活动中,您都应覆盖onResume()onPause()并将标志设置为相应的值:

Now in every activity that you have you should override onResume() and onPause() and set the flag to the corresponding value:

class BaseActivity extends Activity {


    @Override
    protected void onResume() {
        super.onResume();
        ((MyAppContext)getApplication()).setIsAppRunning(true);
    }

    @Override
    protected void onPause() {
        ((MyAppContext)getApplication()).setIsAppRunning(false);
        super.onPause();
    }
}

这样,每次启动一个Activity时,MyAppContext中的isAppRunning值将为true,当退出Activity时它将为false,但是如果另一个Activity打开(例如您按下后退按钮,以便您返回上一个活动),该值将立即再次变为true.

On this way every time you start an Activity the value of isAppRunning in MyAppContext will be true, when you exit the Activity it will be false but if another Activity opens (for example if you pressed the back button so you are returning to the previous activity) the value will be immediately true again.

当您最终完成所有活动时,不会调用任何onResume()方法,而将调用所有onPause()方法,因此isAppRunning将是false,并且您知道Activity不再处于打开状态前景.

When you finally finish all your Activities none of the onResume() methods will be called and all the onPause() methods will be called so isAppRunning will be false and you know your Activity is no longer on the foreground.

因此,如果isAppRunningtrue,则您的应用程序位于前台(开始会话跟踪),否则它消失了(停止会话跟踪).您可以在MyAppContext类中创建一个Timer,以定期检查isAppRunning的值,因此它将是:

So resuming, if isAppRunning is true your application is on the foreground (start the session tracking) otherwise it's gone (stop the session tracking). You can create a Timer in MyAppContext class to check the value of isAppRunning periodically, so it would be:

public class MyAppContext extends Application {

   public boolean isAppRunning = true;
   public final int timerRate = 500;    // Execute timer task every 500mS

   public void setIsAppRunning(boolean v){
      isAppRunning = v;
   }

   public boolean isAppRunning(){
      return isAppRunning;
   }

   @Override
   public void onCreate() {
      super.onCreate();
      Timer mTimer = new Timer();

      mTimer.scheduleAtFixedRate(new TimerTask() {
         @Override
         public void run() {
            if(isAppRunning) startSesionTracking();
            else stopSesionTracking();
         }
      }, 0, REFRESH_TIME);
   }

   private void startSesionTracking () { ... };
   private void stopSesionTracking () { ... };

}

您应根据会话跟踪中要获得的精度来修改timerRate.

You should modify timerRate according to the precision you want to get in your session tracking.

这篇关于Android应用程序的开始和结束事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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