【问题标题】:Why is my widget not runnng?为什么我的小部件没有运行?
【发布时间】:2017-07-19 13:14:02
【问题描述】:

您好,您能看到这些 sn-ps 并告诉我为什么我的服务在调用 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-------------*/

}

【问题讨论】:

  • 你没有关闭 Realm?

标签: android android-widget factory remoteview android-remoteview


【解决方案1】:

问题已解决。原来我忘了调用下面的一些方法:

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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-03
    • 2017-12-01
    相关资源
    最近更新 更多