Код манифеста:
Код: Выделить всё
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.receivertest"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="19" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".MyBroadcastReceiver" >
<intent-filter android:priority="2147483647" >
<action android:name="android.intent.action.MEDIA_BUTTON" />
</intent-filter>
</receiver>
</application>
</manifest>Код: Выделить всё
package com.example.receivertest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
public class MyBroadcastReceiver extends BroadcastReceiver {
public MyBroadcastReceiver() {
super();
}
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(Intent.ACTION_HEADSET_PLUG)) {
if (intent.getExtras().getInt("state") == 1)// if plugged
Toast.makeText(context, "earphones plugged", Toast.LENGTH_LONG)
.show();
else
Toast.makeText(context, "earphones un-plugged",
Toast.LENGTH_LONG).show();
} else if (action.equals(Intent.ACTION_MEDIA_BUTTON)) {
Toast.makeText(context, "button pressed", Toast.LENGTH_LONG).show();
String key = intent.getExtras().getString("EXTRA_KEY_EVENT");
Toast.makeText(context, key, Toast.LENGTH_LONG).show();
}
}
}Код: Выделить всё
package com.example.receivertest;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioManager;
import android.os.Build;
import android.os.Bundle;
public class MainActivity extends Activity {
MyBroadcastReceiver myBroadcastReceiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Получаем доступ к менеджеру звуков
myBroadcastReceiver = new MyBroadcastReceiver();
IntentFilter mediaFilter = new IntentFilter(Intent.ACTION_MEDIA_BUTTON);
mediaFilter.setPriority(2147483647);
if (Build.VERSION.SDK_INT < 10)
registerReceiver(myBroadcastReceiver, mediaFilter);
else
((AudioManager) getSystemService(AUDIO_SERVICE))
.registerMediaButtonEventReceiver(new ComponentName(this,
MyBroadcastReceiver.class));
registerReceiver(myBroadcastReceiver, new IntentFilter(
Intent.ACTION_HEADSET_PLUG));
}
}