如何在java中将耳机连接到手机时启动应用

时间:2016-11-03 10:03:45

标签: java android android-studio

当耳机或耳机连接到移动设备时,如何启动应用或活动?我在另一个关于广播接收器的网站上阅读了一些例子。我是android开发新手,感谢写的例子。

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;
            }
        }
    }
}

但此代码在应用程序运行时有效。

1 个答案:

答案 0 :(得分:1)

对您的清单文件尝试此权限。

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