アプリケーションにウィジェットを追加しました。基本的に、ウィジェットをクリックするとサービスが有効になります。ただし、ウィジェットを押さなくても、サービスがランダムに有効になることがあります
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 をクリックしたときにサービス インテントを実行する必要があります。クリックすると正常に機能しますが、ランダムな有効化が行われます (サービスが有効化されると通知が表示されるので、サービスが実行中であることがわかります)。