0

(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.)

Community
  • 1
  • 1
sl33nyc
  • 43
  • 4

1 Answers1

2

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

Nathaniel D. Waggoner
  • 2,856
  • 2
  • 19
  • 41
  • Yeah, I'm statically defining my receiver, just like your example. However, my receiver doesn't seem to receive the intent, specified in the intent-filter, if the application hasn't been started (eg. upon device boot up). – sl33nyc Jan 10 '14 at 21:54
  • Are you sure you have the intents right? Is your receiver defined in it's own class, or in as a NestedClass? The way you declare these is slightly different. Any log output you can post? Also - make sure to run your app once, as android has a security feature that certain intents (like on boot) won't work without the app having been run once. – Nathaniel D. Waggoner Jan 10 '14 at 22:02