過去1週間から同じ状況に直面しました。あなたに役立つかもしれないより良い解決策を見つけました。
アクティビティが現在実行中のアクティビティであるかどうかを確認するには
boolean isNotificationRequired = true;
ActivityManager am = (ActivityManager) this.getSystemService(ACTIVITY_SERVICE);
List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);
Log.d("TEST", "CURRENT Activity ::" + taskInfo.get(0).topActivity.getClassName());
ComponentName componentInfo = taskInfo.get(0).topActivity;
componentInfo.getPackageName();
マニフェスト ファイルに追加
<uses-permission android:name="android.permission.GET_TASKS" />
Now アクティビティが現在実行中のアクティビティである場合、操作を実行します。
if(taskInfo.get(0).topActivity.getClassName().equals(YOUR_CURRENT_ACTIVITY.class.getName())
{
//Perform the Operations
isNotificationRequired = false;
}
isNotificationRequired が true の場合にのみ通知を送信するようになりました。
if(isNotificationRequired){
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
this).setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("Notification Title")
.setContentText("Notification Message");
PendingIntent notifyIntent = PendingIntent.getActivity(this, requestcode,
resultIntent, PendingIntent.FLAG_ONE_SHOT);
mBuilder.setContentIntent(notifyIntent);
mBuilder.setAutoCancel(true);
mBuilder.setDefaults(Notification.DEFAULT_VIBRATE
| Notification.DEFAULT_SOUND | Notification.DEFAULT_LIGHTS);
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(requestcode, mBuilder.build());
}
それ以外の場合は、ブロードキャストを送信してアクティビティを更新してください。
(私にとって、既存のインテントを送信すると、レシーバーで適切に受信されません。そのため、新しいインテントを作成し、既存のインテントのデータをこの newIntent の putExtras() に渡しました。)
else {
Log.i("TEST", "Sending broadcast to activity");
Intent newIntent = new Intent();
newIntent.setAction("TestAction");
sendBroadcast(newIntent);
}
次に、アクティビティで、ブロードキャスト レシーバーを作成してブロードキャストを処理します。インスタンス化することを忘れないでください。manifest.xml でレシーバーを指定する必要はありません。
public class YourCurrentRunningActivity extends Activity {
YourBroadcastReceiver receiver = new YourBroadcastReceiver();
protected void onCreate(Bundle savedInstanceState) {
(this).registerReceiver(receiver, new IntentFilter("TestAction"));
public class YourBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context arg0, Intent arg1) {
// Perform the Actions u want.
}
}
}
次に、次のように onStop()/onPause()/onDestroy() でレシーバーの登録を解除できます。
this.unregisterReceiver(receiver);