如果 activity 是 运行 则发送 LocalBroadcast 否则从后台服务发送通知

Send LocalBroadcast if activity is running else send notification from a background service

如果 Activity 是 运行,我需要使用 LocalBroadcast 从后台服务更新我的 Activity。如果申请或Activity目前不是运行,我想添加一个待定通知。

我浏览了以下帖子 -

Check if activity is running from service

Activity or Notification via Ordered Broadcast

我有以下疑问 -

如果还有其他解决方案,也请分享。

我在过去一周遇到了同样的情况。我发现了一个更好的解决方案,可能会对您有所帮助。

查找activity是否是当前运行activity服务

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" />

如果 activity 是当前的 运行 activity.

现在执行操作
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());    
}

否则,发送广播并更新您的 activity。

(对我来说,如果我发送现有的意图,它没有在接收器中正确接收。所以我创建了新的意图并在这个 newIntent 的 putExtras() 中传递了现有意图的数据。)

else {
            Log.i("TEST", "Sending broadcast to activity");
            Intent newIntent = new Intent();
            newIntent.setAction("TestAction");
            sendBroadcast(newIntent);
     }

然后在您的 activity 中通过创建广播接收器来处理广播。不要忘记实例化。无需在 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);