简体   繁体   中英

Persistent BroadcastReceiver

(I haven't found the following question clearly answered elsewhere, so I'll ask here.)

I subclassed BroadcastReceiver to capture new photos being captured. This subclass works great, but if my application's process isn't alive, my custom BroadcastReceiver also isn't running and hence doesn't trigger when relevant intents are sent.

What's the recommended approach for a persistent (truly, not if my application is running) BroadcastReceiver? I get the impression that I should use a Service, but it's not clear to me what goes into my Service other than:

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    return START_STICKY;
}

which, I believe, persists the Service. Otherwise, it seems strange to me that the BroadcastReceiver, the one that's actually referenced in my AndroidManifest.xml, has no reference in my Service.

(On a side note, I have another custom BroadcastReceiver, whose sole purpose is to start the aforementioned Service upon device startup. Thank you, Android BroadcastReceiver on startup .)

You can use intent filters in your manifest to trigger you broadcast receiver like so:

 <receiver android:name="MyReceiver" >
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED" />
        </intent-filter>
</receiver>

This should get your receiver to receive events even when the app is closed.

Define your receiver like so:

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

public class MyReceiver extends BroadcastReceiver {

  @Override
  public void onReceive(Context context, Intent intent) {
    Intent service = new Intent(context, WordService.class);
    context.startService(service);
  }
} 

Slightly editied from this tutorial:

http://www.vogella.com/tutorials/AndroidBroadcastReceiver/article.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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