我想使用broadcastReceiver来捕捉我的Android应用程序的耳机按钮点击,但它似乎没有传递到我的接收器类。我看了很多问题,但没有合适的答案。谢谢。
PS:对不起我的英文;)
这是我的主要活动:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton)findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
IntentFilter filter = new IntentFilter(Intent.ACTION_MEDIA_BUTTON);
HeadsetReceiver r = new HeadsetReceiver();
filter.setPriority(1000);
registerReceiver(r, filter);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
我的BroadcastReceiver类:
public class HeadsetReceiver extends BroadcastReceiver {
private final String ACTION_BUTTON_HEADSET = "android.intent.action.MEDIA_BUTTON";
@Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals(ACTION_BUTTON_HEADSET)){
System.out.println("Just a test");
}
}
}
我的清单:
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<receiver class="mypackage.HeadsetReceiver"
android:name="mypackage.HeadsetReceiver">
<intent-filter android:priority="100">
<action android:name="android.intent.action.MEDIA_BUTTON" />
</intent-filter>
</receiver>
<activity
android:name=".MainActivity"
android:label="@string/app_name"
android:theme="@style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
答案 0 :(得分:0)
您还必须将接收器注册为音频管理器。您可以在活动的onCreate中执行此操作:
AudioManager audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
audioManager.registerMediaButtonEventReceiver(
new ComponentName(this, HeadsetReceiver.class));
您也可以删除IntentFilter代码,因为它已在清单中定义。