【问题标题】:Android Widget+ServiceAndroid 小部件+服务
【发布时间】:2014-06-26 13:21:09
【问题描述】:

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

我对小部件完全陌生,所以我看过一些教程。但它们对我帮助不大 我对未决意图完全陌生。我现在很困惑,请帮帮我...... 我想要做的只是使用小部件的按钮触发服务内的广播......

这是我一直试图理解的复制粘贴代码

 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

【问题讨论】:

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


    【解决方案1】:

    创建一个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);
    

    然后,更改您的清单以处理在PendingIntent 中传递的Action

       <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 并启动。检查onStartCommand中的Action

    @Override
    public int onStartCommand(Intent intent, int flag, int startId) {
    
        if(intent.getAction().equalsIgnoreCase("com.example.app.ACTION_PLAY")){
            // do your stuff here
        }
    

    您可以为Widget 中的所有必需视图设置类似的自定义Actions

    在这里查看编译代码https://gist.github.com/androidbensin/4a9f044ac0b3110c049e

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

    【讨论】:

    • 请告诉我是否可以使用广播代替??
    • 我可以在服务内触发广播吗
    • 是的,你可以使用。在这里查看我的答案stackoverflow.com/questions/23443946/…
    • 是的。小部件或通知无关紧要。它关于远程视图的未决意图
    • 嗨,但是这个广播已经在它自己的类中定义了,对吧?我在服务中有这个广播......当广播在另一个类中时,它们没有在清单中注册,但它们被注册为这个
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-05
    • 1970-01-01
    相关资源
    最近更新 更多