0

你好,你可以这么善良看到thoose片段,并告诉我为什么我的服务无法启动后调用startService()。我正在尝试创建一个Widget,它为屏幕上的所有窗口小部件运行一项服务。该服务提供了一个工厂来填充列表视图。我对小部件很陌生,所以如果我做错了什么,请提醒我。为什么我的小部件不能运行?

这是窗口小部件提供程序类:

public class MyWidProvider extends AppWidgetProvider { 

    @Override 
    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { 
     RemoteViews rv = new RemoteViews(context.getPackageName(), R.layout.widget_list_view); 
     rv.setEmptyView(R.id.mywid_listview, R.id.empty_view); 
     appWidgetManager.updateAppWidget(appWidgetIds, rv); 
     Log.d("MyWidProvider", "start service <<<<<<<<<"); 
     //here I am starting the service 
     Intent intent = new Intent(context, MyWidService.class); 
     context.startService(intent); 
     super.onUpdate(context, appWidgetManager, appWidgetIds); 

    } 

} 

这是服务:

public class MyWidService extends RemoteViewsService { 
    Realm realm; 
    @Override 
    public MyWidFactory onGetViewFactory(Intent intent) { 
     Log.d("MyWidService", " onGetViewFactory()<<<<<<<<<<"); 
     Context context = getApplicationContext(); 
     Realm.init(context); 
     realm = Realm.getDefaultInstance(); 
     realm.isAutoRefresh(); 
     populateRealm(); 
     return new MyWidFactory(context, intent, realm); 
    } 

    private void populateRealm() { 
     realm.executeTransaction((t) ->{ 
      final Task myTask = realm.createObject(Task.class); 
      myTask.setText("this is random widget Task"); 
      final Task myTask2 = realm.createObject(Task.class); 
      myTask2.setText("this is my second widget task"); 
     }); 
    } 

} 

,这是工厂:

class MyWidFactory implements RemoteViewsService.RemoteViewsFactory { 
    private Context mContext; 
    private RealmResults<Task> tasks; 
    private Realm realm; 
    MyWidFactory(Context context, Intent intent, Realm realm) { 
     mContext = context; 
     this.realm = realm; 
    } 
    // Initialize the data set. 
    public void onCreate() { 
     Log.d("MyWidFactory", "onCreate() <<<<<<<<"); 
     tasks = realm.where(Task.class).findAll(); 
    } 
/*-------------------more methods-------------*/ 

} 

回答

0

问题固定。原来我忘了拨打下面的一些方法:

Intent intent = new Intent(context, MyWidService.class); 
intent.setData(Uri.parse(intent.toUri(Intent.URI_INTENT_SCHEME))); 
rv.setRemoteAdapter(R.id.mywid_listview, intent); 
context.startService(intent); 
appWidgetManager.notifyAppWidgetViewDataChanged(appWidgetIds, R.id.widget_list_text); 
appWidgetManager.updateAppWidget(appWidgetIds, rv); 
相关问题