I want to be alerted, if a headset is plugged in. But the Intent "ACTION_HEADSET_PLUG" is used with the Flag "FLAG_RECEIVER_REGISTERED_ONLY".
So I have to run a service or a activity all the time to get the intent? I just want to run a Broadcastreceiver and NO service or activity at all. Is there a workaround for this? Is this even possible? Or can I start a service once, registering and then stopping it?
P.S.: I know when the headset is plugged off with the becoming noisy intent.
Thank you for you answers.
Dianne Hackborn says
It's only given to those who call registerReceiver, and not sent to
receivers declared in manifests.
So you have to have something running that calls registerReceiver
. It that stops running and you don't unregister the receiver you get an error.
There are components that should be registered when the application is installed (<3.0), or at least when the application has moved from stopped state to started (3.0 & ICS), such as a ContentProvider
.
The provider apparently doesn't have an "end" to it's life cycle that you have to worry (a lot) about.
Simply put, adding a <provider>
to your AndroidManifest.xml
:
<provider android:name=".ReceiverProvider"
android:authorities="some.provider.authority.goes.here"
android:exported="true" />
And, for the ReceiverProvider
:
public class ReceiverProvider extends ContentProvider {
@Override
public boolean onCreate() {
BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
System.out.println("Headset plug: " + intent);
}
};
IntentFilter filter = new IntentFilter(Intent.ACTION_HEADSET_PLUG);
getContext().registerReceiver(receiver, filter);
return true;
}
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
String sortOrder) {
return null;
}
@Override
public String getType(Uri uri) {
return null;
}
@Override
public Uri insert(Uri uri, ContentValues values) {
return null;
}
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
return 0;
}
@Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
return 0;
}
}
Worth trying perhaps.