Android Widget +服务

时间:2014-05-08 22:40:37

标签: android android-widget android-service android-broadcast

我有一个使用服务播放音乐的音乐播放器,该服务中的所有广播接收器都是在服务内部而非外部定义的。

我对小工具全新,所以我看过一些教程。但是他们对我帮助不大 我对待定意图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 enter image description here

1 个答案:

答案 0 :(得分:0)

创建custom Intent Action并将其设置为PendingIntentwidget项(您的案例中的按钮)

 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

希望你现在好。如果有任何问题,请告诉我