studio apk studio apk - 7 months ago 43
Android Question

How to start app when headset connected to phone in java

How could start app or activity when headphone or headset connected to mobile it's possible ? i read some example in another site about broadcast receiver.i'm new in android developing thanks if write example.

private class MusicIntentReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_HEADSET_PLUG)) {
int state = intent.getIntExtra("state", -1);
switch (state) {
case 0:
Toast.makeText(MainActivity.this, "unplug", Toast.LENGTH_SHORT).show();
break;
case 1:
Toast.makeText(MainActivity.this, "plug", Toast.LENGTH_SHORT).show();
break;
default:

}
}



public class MusicIntentReceiver extends WakefulBroadcastReceiver {
public void onReceive(Context ctx, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_HEADSET_PLUG)) {
int state = intent.getIntExtra("state", -1);
switch (state) {
case 0:
Toast.makeText(ctx, "unplug", Toast.LENGTH_SHORT).show();
break;
case 1:
Toast.makeText(ctx, "plug", Toast.LENGTH_SHORT).show();
break;
}
}
}
}


but this code work when application is running.

Answer

try this permission to your manifest file.

<receiver
    android:name="AudioJackReceiver"
    android:enabled="true"
    android:exported="true" >
    <intent-filter>
        <action android:name="android.intent.action.HEADSET_PLUG" />
    </intent-filter>
</receiver>