1

我为我的应用程序添加了一个小部件,基本上点击小部件可以启用服务。但有时即使我没有按下小部件,我也会随机启用服务

我按照android开发人员指南制作小部件,代码如下所示

public class ToggleWidget extends AppWidgetProvider {

    static RemoteViews remoteViews;
    boolean status = false;

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

        final int N = appWidgetIds.length;

        // Perform this loop procedure for each App Widget that belongs to this provider
        for (int i=0; i<N; i++) {
            int appWidgetId = appWidgetIds[i];

            remoteViews = new RemoteViews(context.getPackageName(), R.layout.toggle_widget);
            Intent intent = new Intent(context.getApplicationContext(), WakeService.class);
            intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, appWidgetIds);
            PendingIntent pendingIntent = PendingIntent.getService(
                    context.getApplicationContext(), 0, intent,
                    PendingIntent.FLAG_UPDATE_CURRENT);
            remoteViews.setOnClickPendingIntent(R.id.bulb_widget, pendingIntent);
            appWidgetManager.updateAppWidget(appWidgetIds, remoteViews);

            context.startService(intent);

            Log.w(getClass().getName(), "Widget Worked");


         // Tell the AppWidgetManager to perform an update on the current app widget
            appWidgetManager.updateAppWidget(appWidgetId, remoteViews);
        }
    }




}

当我单击 ImageButton 时,此代码应运行服务意图。单击它可以正常工作,但是我得到了那些随机启用(该服务在启用时会显示一条通知,所以我知道它正在运行)您能在代码中发现一些错误吗?

4

1 回答 1

1

取出

context.startService(intent);

由于在PendingIntent单击小部件时已经启动了服务,因此无论是否单击小部件,显式context.startService()in都会使服务启动。onUpdate()

于 2013-01-02T23:11:17.977 回答