过去一周我也面临同样的情况。我找到了一个更好的解决方案,可能会对您有所帮助。
查找该活动是否是服务中当前正在运行的活动
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" />
现在如果活动是当前正在运行的活动,则执行该操作。
if(taskInfo.get(0).topActivity.getClassName().equals(YOUR_CURRENT_ACTIVITY.class.getName())
{
//Perform the Operations
isNotificationRequired = false;
}
现在仅当 isNotificationRequired 为真时才发送通知。
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);