如果Android的活动运行发现 [英] Discovering if Android activity is running

查看:91
本文介绍了如果Android的活动运行发现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用C2DM,我BroadcastReceivers传播C2DM事件到本地服务。服务完成注册通过发送ID到我的网络服务器脓是负责让设备了解新的信息,但是如果应用程序(的活动之一),是由我们要发送的意图,该活动与新数据,因此它可以更新,如果不大于NotificationManager用于通知用户。

I'm using C2DM, my BroadcastReceivers propagate the C2DM events to a local service. the service complete the registration by sending the id to my webserver pus it's responsible for letting the device know about new messages, however if the application (one of the activities) is up we want to send an intent to that activity with the new data so it can be updated, if not than the NotificationManager is used to notify the user.

问题是,如何知道该活动运行? Application对象是不是一种选择,因为服务是应用程序这显然将是present的一部分。注销在每个应用的onDesroy也不是一种选择,因为它可能会出现在定向变化...

The issue is, how to know the activity is running ? the Application object is not an option since the Service is part of the application it's obviously going to be present. unregister in the onDesroy of each application is also not an option since it may occur in orientation change...

任何标准的方式来完成它?

Any standard way to get it done ?

推荐答案

解决方案1: 您可以使用<一个href="http://developer.android.com/reference/android/app/ActivityManager.html#getRunningAppProcesses">ActivityManager因为如果检查活动是否运行:

Solution 1: You can use ActivityManager for Checking if Activity is Running or not:

public boolean isActivityRunning() { 

ActivityManager activityManager = (ActivityManager)Monitor.this.getSystemService (Context.ACTIVITY_SERVICE); 
    List<RunningTaskInfo> activitys = activityManager.getRunningTasks(Integer.MAX_VALUE); 
    isActivityFound = false; 
    for (int i = 0; i < activitys.size(); i++) { 
        if (activitys.get(i).topActivity.toString().equalsIgnoreCase("ComponentInfo{com.example.testapp/com.example.testapp.Your_Activity_Name}")) {
            isActivityFound = true;
        }
    } 
    return isActivityFound; 
} 

需要的权限添加到您的清单。

need to add the permission to your manifest..

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

解决方案2: 您可以使用您的活动您要检查它的运行与否并存储一些地方从服务接入或广播接收机作为一个静态变量:

Solution 2: Your can use an static variable in your activity for which you want to check it's running or not and store it some where for access from your service or broadcast receiver as:

static boolean CurrentlyRunning= false;
      public void onStart() {
         CurrentlyRunning= true; //Store status of Activity somewhere like in shared //preference 
      } 
      public void onStop() {
         CurrentlyRunning= false;//Store status of Activity somewhere like in shared //preference 
      }

我希望这是有帮助的!

这篇关于如果Android的活动运行发现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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