应用生命周期和广播接收器

时间:2012-12-29 11:08:56

标签: android broadcastreceiver broadcasting

我想知道当你在主要活动中创建一个广播接收器时会发生什么(在我的情况下是一个接近警报接收器),并且应用程序进程因某种未知原因被杀死了?

我希望在广播接收器i注册中接收我的接近警报,无论我的应用程序状态如何,是否会发生这种情况,或者我是否需要特别做些什么来确保?

编辑澄清:

我必须在我的应用程序中注册接收器而不是通过清单。由于我需要多个感应区域,因此对于每个(变化的)位置,我将需要动态创建接收器,因为我需要为每个位置注册接收器,遗憾的是具有唯一ID。

创建我的意图/ pendingintent / broadcastreceiver的代码:

    double latitude = location.getLat();
    double longitude = location.getLon();
    Intent intent = new Intent(PROX_ALERT_INTENT_ID);
    PendingIntent proximityIntent = PendingIntent.getBroadcast(activity.getApplicationContext(), 0, intent, 0);
    lm.addProximityAlert(
        latitude, // the latitude of the central point of the alert region
        longitude, // the longitude of the central point of the alert region
        POINT_RADIUS, // the radius of the central point of the alert region, in meters
        PROX_ALERT_EXPIRATION, // time for this proximity alert, in milliseconds, or -1 to indicate no                           expiration
        proximityIntent // will be used to generate an Intent to fire when entry to or exit from the alert region is detected
    );

    IntentFilter filter = new IntentFilter(PROX_ALERT_INTENT_ID);

    activity.registerReceiver(new ProximityIntentReceiver(location), filter);

2 个答案:

答案 0 :(得分:3)

如果您想要触发BroadcastReceivers,无论您的应用是什么状态,那么您应该通过应用AndroidManifest.xml文件注册它们。

Heres怎么做。

  1. 定义扩展BroadcastReceiver的类并实现onReceive()方法。 我看到你已经这样做了 - ProximityIntentReceiver就是那个班级。

  2. 在AndroidManifest.xml文件中添加:

    <application>
    ...
        <receiver
            android:name=".MyReceiver"
            android:exported="false" >
            <intent-filter>
                   <action android:name="my.app.ACTION" />
            </intent-filter>
        </receiver> 
    </application>
    
  3. 其中MyReceiver是您的接收者类的名称(在您的情况下为ProximityIntentReceiver),而my.app.ACTION是您的接收者将要侦听的动作(在您的情况下,我猜它是PROX_ALERT_INTENT_ID)的值。

    注意:说明接收者的姓名为.MyReceiver,假设它位于您应用的根目录包中。如果不是这种情况,那么您需要从根目录开始提供该类的路径。

答案 1 :(得分:0)

@Mathias:即使应用程序被杀,我动态注册广播接收器并处于活动状态的方式是运行服务并从那里注册接收器。希望它有所帮助。

相关问题