gpt4 book ai didi

android - 使用没有 Activity 的服务的媒体按钮(耳机 Hook )的监听器

转载 作者:行者123 更新时间:2023-11-29 17:57:22 27 4
gpt4 key购买 nike

如何让服务监听 android 设备中的媒体按钮(耳机 Hook )。我尝试使用这段代码来做到这一点,但没有奏效。你能帮帮我吗。

服务代码:

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>

提前谢谢你。

最佳答案

您的服务需要一个 IntentACTION_MEDIA_BUTTON Intent行动。您没有使用这样的 Intent 启动服务.

改变:

    Intent i=new Intent(RLservice.class.getName());
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
arg0.startService(i);

到:

    arg1.setClass(this, RLservice.class);
arg0.startService(arg1);

这将有效地将广播作为命令“重定向”到您的服务,并且 Action 和附加功能完好无损。

还有:

  • 去掉android:process=":remote" ,因为这里没有必要,而且对用户不利

  • 摆脱你的 <intent-filter>在你的<service> ,除非您打算让一百万个其他应用程序调用此服务

关于android - 使用没有 Activity 的服务的媒体按钮(耳机 Hook )的监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18423893/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com