如何让服务监听 android 设备中的媒体按钮(耳机挂钩)。我尝试使用此代码来做到这一点,但没有奏效。你能帮助我吗。
服务代码:
public class RLservice extends IntentService {
private Handler handler;
public RLservice() {
super("my service");
// TODO Auto-generated constructor stub
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
handler = new Handler();
return super.onStartCommand(intent, flags, startId);
}
@Override
protected void onHandleIntent(Intent arg0) {
String intentAction = arg0.getAction();
if (Intent.ACTION_MEDIA_BUTTON.equals(intentAction)) {
KeyEvent event = (KeyEvent) arg0
.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
if (event == null) {
return;
}
int keycode = event.getKeyCode();
int action = event.getAction();
long eventtime = event.getEventTime();
if (keycode == KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE
|| keycode == KeyEvent.KEYCODE_HEADSETHOOK) {
if (action == KeyEvent.ACTION_DOWN) {
// Start your app here!
handler.post(new Runnable() {
public void run() {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "Welcome",
Toast.LENGTH_LONG).show();
}
});
}
}
}
}
}
这是接收方代码:
public class RLreciver extends BroadcastReceiver
{
@Override
public void onReceive(Context arg0, Intent arg1) {
// TODO Auto-generated method stub
Intent i=new Intent(RLservice.class.getName());
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
arg0.startService(i);
}
}
这很明显:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.ypu.RLservice"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="10" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<receiver android:name=".RLreciver" >
<intent-filter android:priority="100000" >
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.MEDIA_BUTTON" />
</intent-filter>
</receiver>
<service
android:name=".RLservice"
android:process=":remote" >
<intent-filter>
<action android:name="com.ypu.RLservice.RLservice" />
</intent-filter>
</service>
</application>
</manifest>
先感谢您。