你好,你能看到那些片段并告诉我为什么我的服务在调用后没有启动startService()
。我正在尝试创建一个 Widget ,它为屏幕上的所有小部件运行一项服务。该服务提供了一个工厂来填充列表视图。我是小部件的新手,所以如果我做错了什么,请警告我。
这是 Widget Provider 类:
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-------------*/
}