简体   繁体   English

通过意图将数据从服务传递到小部件

[英]Pass data from a service to widget via intents

I've got a service which calls an intent to send a custom text to my AppWidgetProvider.我有一个服务,它调用一个向我的 AppWidgetProvider 发送自定义文本的意图。 For this I use the onRecieve method and check for the right action.为此,我使用 onRecieve 方法并检查正确的操作。

So I have two questions, the first one is, is this the right way and the second why is my onReceive method never get called?所以我有两个问题,第一个是,这是正确的方法,第二个为什么我的 onReceive 方法永远不会被调用?

I added the manifest this following part我在以下部分添加了清单

<receiver android:label="KreativBarometer Widget"
   android:name=".widget.MyWidgetProvider" >
   <intent-filter >
      <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
   </intent-filter>
   <meta-data
       android:name="android.appwidget.provider"
       android:resource="@xml/widget_info" />
 </receiver>

My AppWidgetProvider use the following onReceive method我的 AppWidgetProvider 使用以下 onReceive 方法

public void onReceive(Context context, Intent intent) {
    if(intent.getAction().equals("APPWIDGET_UPDATE")){
        String text = intent.getStringExtra("newItemArrived");
        RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget_layout);
        views.setTextViewText(R.id.TextView01, text);
    }
    super.onReceive(context, intent);
}

and for testing I use this intent并且为了测试我使用这个意图

Intent intent = new Intent("APPWIDGET_UPDATE");
intent.putExtra("newItemArrived", "Neue Frage erschienen");
sendBroadcast(intent);

I think you have to modify your manifest file to include two things : 我认为您必须修改清单文件以包括两件事:

  1. One more action in your <receiver> to indicate you have an intent coming into your widget <receiver>中的另一项操作,表明您有意图加入小部件

  2. Register your service. 注册您的服务。

Perhaps this video would be useful : https://youtu.be/DJsNmS-PvD8?t=2m7s 也许这段视频会有用: https : //youtu.be/DJsNmS-PvD8?t=2m7s

To pass custom date you need to use a Bundle as:要传递自定义日期,您需要使用 Bundle 作为:

val intent = Intent(context, ItemsCollectionRemoteViewsService::class.java)
            .apply {
                val extrasBundle = Bundle()
                extrasBundle.putSerializable(WIDGET_DATA, widgetData)
                putExtra(WIDGET_Bundle_DATA, extrasBundle)
            }
        remoteViews.setRemoteAdapter(R.id.items_list_view, intent)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM