0

Hello can you be so kind to see thoose snippets and tell me why my service doesnt start after calling startService(). I am trying to create a Widget , that runs one service for all widgets on the screen. That service provide a factory to populate a list view. I am new to widgets so if I am doing something wrong please warn me about it.

This is the Widget Provider class:

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

    }

}

this is the Service:

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

}

and this is the Factory:

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-------------*/

}
Vlad Skurtolov
  • 1,024
  • 1
  • 7
  • 20

1 Answers1

0

Problem fixed. Turns out I forgot to call some of the methods below:

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);
Vlad Skurtolov
  • 1,024
  • 1
  • 7
  • 20