簡體   English   中英

在Java中將耳機連接到手機時如何啟動應用程序

[英]How to start app when headset connected to phone in java

當耳機或頭戴式耳機連接到手機時,如何啟動應用程序或活動? 我在另一個站點上閱讀了一些有關廣播接收器的示例。我是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;
            }
        }
    }
}

但是此代碼在應用程序運行時有效。

對清單文件嘗試此權限。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM