hyoromoのブログ

最近はVRSNS向けに作ったものについて書いています

AppWidgetからIntentでService起動したときの問題

ボタンを使った AppWidget の場合、ボタンが押された事をトリガーに Intent を投げる仕組みを作るであろう。
その際、Activity なら何も問題は発生しないのだが、Service の場合は致命的なバグを生んでしまうかもしれない。

障害

まずは以下のソースを見て頂きたい。

AppWidgetManager manager = AppWidgetManager.getInstance(context);
RemoteViews views = new RemoteViews(context.getPackageName(),R.layout.widget_layout);
Intent intent = new Intent(context, サービスクラス.class);
PendingIntent pendingIntentBet = PendingIntent.getService(context, 0, intent, 0);
views.setOnClickPendingIntent(R.id.ボタン, pendingIntentBet);
manager.updateAppWidget(new ComponentName(context, ウィジェットクラス.class), views);

おおよその人がこのように PendingIntentクラスを用いた実装を行うであろう。確かにこれは正解であり、このままで何の問題も無い。
が、しかし。
Home画面の向きを変えてみましょう*1...するとWidgetをタッチしたときにServiceが起動しなくなります。

解決

AppWidget側の実装はそのままで、Service側に以下の実装を追加する。

AppWidgetManager manager = AppWidgetManager.getInstance(context);
RemoteViews views = new RemoteViews(context.getPackageName(),R.layout.widget_layout);
Intent intent = new Intent(context, サービスクラス.class);
PendingIntent pendingIntentBet = PendingIntent.getService(context, 0, intent, 0);
views.setOnClickPendingIntent(R.id.ボタン, pendingIntentBet);
manager.updateAppWidget(new ComponentName(context, ウィジェットクラス.class), views);

これは[障害]に書いたコードとまったく同じです。

何が言いたいかというと、Service側で Intent 情報の再定義をしなければいけないようです。

まとめ

理由は不明でしたが、一応解決はできました。
これはスマートな解決方法ではないので、他に手立てがないかを時間があるときに調査してみたいと思います。

*1:ハードキーボードを出す