Notificationでクリックすると別のプロセスになるのを対策(途中)
メインのActivityからサービスを起動して、サービス内でタイマーでDBに書き込んで更新があったらメインのListに表示させるっていうプログラムを作成しています。
ここで、メインとのやり取り方法で昨日まで躓いていました。
同じようなものを作ろうとされている方に参考になるかと思い書いておきます。
データベースに書き込む際に、重複チェックをさせています。
追加をしたレコード数をカウントして、新着があるかどうか見ていて、カウントが0じゃないときにNotificationを使ってフロントのアプリと連携を取ろうとしていたのですが、Notificationだと新たにActivityを増やして行ってしまうことがわかりました。
SingleInstanceにする方法というのもあるのですが、その方法を使うとIntentで別のActivitiyから値を受け取れなくなるという罠があるようで、今後の機能に影響が出そうなのでその方法は使えないようです。
いろいろ調べていくうちに、ブロードキャストレシーバーというものがあるそうで、WindowsでいうとIPC通信のようなもの・・・うーんWinAPIの世界でのNamedPipeのようなものかな。
ブロードキャストレシーバーというものを調べていくと、同じアプリ内でつかえるものと、システム全体で使えるものが作れるようで、今回は、同じアプリ内のサービスとアクティビティー間で更新情報のやり取りができれば問題ないので、前者のほうを使います。
メインのアクティビティ側
public class Main extends ListActivity { private IntentFilter intentFilter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //ブロードキャストレシーバー intentFilter=new IntentFilter(); intentFilter.addAction("UPDATE_LIST"); registerReceiver(receiver, intentFilter); //new LogDAO(this).deleteAll(); startService(new Intent(this,ServiceControl.class)); } private BroadcastReceiver receiver=new BroadcastReceiver(){ @Override public void onReceive(Context context, Intent intent) { Bundle bundle = intent.getExtras(); String message = bundle.getString("message"); //トーストでメッセージを表示 Toast.makeText(context, message, Toast.LENGTH_LONG).show(); //リスト更新 loadList(); } };
サービス側
プロセスの有無の確認をするためにmanifesに下記を追加する必要があります。
private void notificationMessage(String msg,int number){ //プロセスが起動しているか確認 if(!isServiceRunning(Main.class.getName())){ //ない場合 PendingIntent pendingIntent=PendingIntent.getActivity(this, 0,new Intent(this,Main.class), 0); Notification notification=new Notification(); notification.icon=R.drawable.ic_launcher; notification.defaults |= Notification.DEFAULT_SOUND; notification.when=System.currentTimeMillis(); notification.number=number; notification.setLatestEventInfo(this, "xxxxxxxxxx", msg, pendingIntent); notificationManager.notify(0, notification); }else { //ブロードキャスト送信 Intent broadcastIntent = new Intent(); broadcastIntent.putExtra( "message", msg); broadcastIntent.setAction("UPDATE_LIST"); getBaseContext().sendBroadcast(broadcastIntent); } } //プロセスが起動しているか boolean isServiceRunning(String className) { ActivityManager am = (ActivityManager)getSystemService(ACTIVITY_SERVICE); List<RunningTaskInfo> taskInfos = am.getRunningTasks(Integer.MAX_VALUE); int serviceNum = taskInfos.size(); for (int i = 0; i < serviceNum; i++) { if (taskInfos.get(i).baseActivity.getClassName().equals(className)) { return true; } } return false; }
これで解決!ならいいのですが、ここまで書いていて、単純にプロセスの有無を見ているだけなのでバックグラウンドで休止状態になっているときはどうなるのかなーという疑問が出てきたので、タイトルに(途中)っていれていますw