服务在不应该的时候启用自身



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

我按照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时运行服务意图。点击它的工作,因为它应该,但我得到那些随机启用(服务显示一个通知,当它被启用,所以我知道它正在运行)你能发现代码中的错误吗?

取出

context.startService(intent);

由于单击小部件时PendingIntent已经启动服务,因此在onUpdate()中显式地设置context.startService()将使服务启动,无论小部件是否被单击

最新更新