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); 
相關問題