服务在不应该的时候启用

时间:2013-01-02 22:55:35

标签: android

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

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

1 个答案:

答案 0 :(得分:1)

取出

context.startService(intent);

由于PendingIntent在单击窗口小部件时已经启动了服务,因此context.startService()中的显式onUpdate()将使服务启动,无论是否单击窗口小部件。< / p>