简体   繁体   English

发现Android活动是否正在运行

[英]Discovering if Android activity is running

I'm using C2DM, my BroadcastReceivers propagate the C2DM events to a local service. 我正在使用C2DM,我的BroadcastReceivers将C2DM事件传播到本地服务。 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. 该服务通过将id发送到我的webserver来完成注册,它负责让设备知道新消息,但是如果应用程序(其中一个活动)已启动,我们希望用新数据向该活动发送意图,它可以更新,如果不是NotificationManager用于通知用户。

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. Application对象不是一个选项,因为Service是应用程序的一部分,它显然会出现。 unregister in the onDesroy of each application is also not an option since it may occur in orientation change... 在每个应用程序的onDesroy中取消注册也不是一个选项,因为它可能会在方向更改中发生...

Any standard way to get it done ? 完成任何标准方法吗?

Solution 1: You can use ActivityManager for Checking if Activity is Running or not: 解决方案1:您可以使用ActivityManager检查活动是否正在运行:

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"/>

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: 解决方案2:您可以在活动中使用静态变量来检查它是否正在运行,并将其存储在服务或广播接收器访问的位置:

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 
      }

I hope this was helpful! 我希望这可以帮到你!

The next approach would work well if you want to handle incoming Google Cloud message (C2DM) by your activity (if any is running) or issue a notification if no activities are running. 如果您希望通过活动处理传入的Google Cloud消息(C2DM)(如果有正在运行),则下一种方法可以正常工作,或者如果没有活动正在运行则发出通知。

Register one BroadcastReceiver in the manifest file. 在清单文件中注册一个BroadcastReceiver。 This receiver will handle C2D messages whenever application not running. 应用程序未运行时,此接收器将处理C2D消息。 Register another BroadcastReceiver programmatically in your activity. 在您的活动中以编程方式注册另一个BroadcastReceiver。 This receiver will handle C2D messages whenever activity is running. 每当活动运行时,此接收器将处理C2D消息。

AndoroidManifest.xml AndoroidManifest.xml

<receiver
    android:name=".StaticReceiver"
    android:permission="com.google.android.c2dm.permission.SEND" >
    <intent-filter>
        <action android:name="com.google.android.c2dm.intent.RECEIVE" />
        <category android:name="com.mypackage" />
    </intent-filter>
</receiver>

MyReceiver.java MyReceiver.java

public class StaticReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        // TODO Trigger a Notification
    }
}

MyActivity.java MyActivity.java

public class MyActivity extends ActionBarActivity {

    @Override
    protected void onResume() {
    super.onResume();

        final IntentFilter filter = new 
                IntentFilter("com.google.android.c2dm.intent.RECEIVE");
        filter.addCategory("com.mypackage");
        filter.setPriority(1); 
        registerReceiver(dynamicReceiver, filter, 
                "com.google.android.c2dm.permission.SEND", null);
    }

    @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver(dynamicReceiver);
    }

    private final BroadcastReceiver dynamicReceiver 
            = new BroadcastReceiver() 
    {
        @Override
        public void onReceive(Context context, Intent intent) {

            // TODO Handle C2DM

            // blocks passing broadcast to StaticReceiver instance
            abortBroadcast();
       }
    };
}

Note! 注意! To catch broadcasts first, the priority of dynamicReceiver IntentFilter must be higher than priority of StaticReceiver instance IntentFilter (default priority is '0'). 要首先捕获广播,dynamicReceiver IntentFilter的优先级必须高于StaticReceiver实例IntentFilter的优先级(默认优先级为'0')。

PS. PS。 It looks like broadcasts issued by Google Cloud Messaging Service are ordered broadcasts. 看起来Google Cloud Messaging Service发布的广播是有序广播。 Original idea author: CommonsWare 原创作者: CommonsWare

Easiest way to check that whether an Activity is running or not is: 检查活动是否正在运行的最简单方法是:

Context context = MyActivity.this; 

if (! ((Activity) context).isFinishing()) {
    //  Activity is running
} else {
    //  Activity has been finished
}

Note: If activity is not running you should not perform any UI related operation. 注意:如果活动未运行,则不应执行任何与UI相关的操作。

Copied from here . 这里复制。

you can use a static variable within the activity. 您可以在活动中使用静态变量。

class MyActivity extends Activity {
     static boolean active = false;

      public void onStart() {
         active = true;
      } 

      public void onStop() {
         active = false;
      }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM