你好,你可以非常友好地看到thoose片段并告诉我为什么我的服务在调用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-------------*/
}
答案 0 :(得分: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);