質問

So, I'm developing an app, that has 5 main functions. I want to make widgets for these functions - each widget provides one function. I've made the 5 layouts, the 5 provider properties xml, and the 5 AppWidgetProvider class. In each provider class I've implemented the onUpdate() method, as you can see in the code below. And sure I have registered them in the manifest file. My problem is, when I click on one of the widgets, it calls the other widgets onUpdate method too and only the last one starts the service. How can I make the 5 widget independent?

One of the provider class:

public class myWidgetProvider extends AppWidgetProvider {
    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {

        final int N = appWidgetIds.length;

        for (int i = 0; i < N; i++) {
            int appWidgetId = appWidgetIds[i];

            String label = appWidgetManager.getAppWidgetInfo(appWidgetId).label;

            Intent intent = new Intent(context, WidgetService.class);
            intent.putExtra(Constants.FUNCTION, Constants.F1);
            PendingIntent pendingIntent = PendingIntent.getService(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

            RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget_f1);
            remoteViews.setOnClickPendingIntent(R.id.widgetF1Button, pendingIntent);

            appWidgetManager.updateAppWidget(appWidgetId, remoteViews);
        }
    }

}

The WidgetService:

    public class WidgetService extends Service {

        @Override
        public int onStartCommand(Intent intent, int flags, int startId) {

            Bundle bundle = intent.getExtras();
            int function = bundle.getInt(Constants.FUNCTION);

            switch (function) {
                case Constants.F1
                      //function1

                case Constants.F2:
                      //funcion2

                case Constants.F3: {
                      //function3

                case Constants.F4: {
                      //function4

                case Constants.F5: {
                      //function5public class WidgetService extends Service {

         }

        return START_STICKY;
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}
役に立ちましたか?

解決

Try using different requestCodes for every pendingIntent:

 PendingIntent pendingIntent = PendingIntent.getService(context, uniqueRequestCode, intent, PendingIntent.FLAG_UPDATE_CURRENT);

It should enable android to differentiate between your pending intents and therefore all buttons will start the service, not just last one. The reason why this should work was discussed here somewhere long time ago - I can try to look it up if you are interested.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top