我有一个使用服务播放音乐的音乐播放器,该服务中的所有广播接收器都是在服务内部而非外部定义的。
我对小工具全新,所以我看过一些教程。但是他们对我帮助不大 我对待定意图soo完全不熟悉。我现在很困惑,请帮帮我... 我想做的只是使用小部件的按钮触发服务内的广播......
以下是我一直试图理解的复制粘贴代码
RemoteViews controlButtons = new RemoteViews(context.getPackageName(),
R.layout.widget);
Intent playIntent = new Intent(context, Music_service.class);
PendingIntent playPendingIntent = PendingIntent.getService(
context, REQUEST_CODE, playIntent, INTENT_FLAGS);
controlButtons.setOnClickPendingIntent(
R.id.bPlay, playPendingIntent);
appWidgetManager.updateAppWidget(appWidgetIds, controlButtons);
这是我的应用程序 :d
答案 0 :(得分:0)
创建custom Intent Action
并将其设置为PendingIntent
到widget
项(您的案例中的按钮)
Intent intent = new Intent("com.example.app.ACTION_PLAY");
PendingIntent pendingIntent = PendingIntent.getService(context.getApplicationContext(), 100,
intent, PendingIntent.FLAG_UPDATE_CURRENT);
RemoteViews remoteViews = new RemoteViews(context.getPackageName(),R.layout.widget_layout);
remoteViews.setOnClickPendingIntent(R.id.bPlay, pendingIntent);
然后,更改您的清单以处理Action
PendingIntent
<service android:name="com.example.app.services.CustomService" >
<intent-filter>
<action android:name="com.mediabook.app.ACTION_PLAY" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</service>
最后,点击播放按钮后,Service
将收到Action
并开始播放。检查Action
onStartCommand
@Override
public int onStartCommand(Intent intent, int flag, int startId) {
if(intent.getAction().equalsIgnoreCase("com.example.app.ACTION_PLAY")){
// do your stuff here
}
您可以为Actions
中的所有必需视图设置类似的自定义Widget
。
请参阅此处的编译代码https://gist.github.com/androidbensin/4a9f044ac0b3110c049e
希望你现在好。如果有任何问题,请告诉我