簡體   English   中英

在 Android 中,當擴展 FirebaseMessagingService 調用 onMessageReceived 時如何獲取當前的 Activity 上下文?

[英]In Android how to get current Activity context when extend FirebaseMessagingService calling on onMessageReceived?

我的集成 FCM 代碼 .. 我想在推送到達時獲取當前活動上下文。 用於使用上下文投射偵聽器的目的。

代碼段在這里...

public class MyFirebaseMessagingService extends FirebaseMessagingService {

private static final String TAG = "MyFMService";
private NotificationListener notificationListener;
private Context context;
private int count=0;

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    Log.d(TAG, "FCM Message Id: " + remoteMessage.getMessageId());

    RemoteMessage.Notification notification = remoteMessage.getNotification();
    Map<String, String> data = remoteMessage.getData();
    Log.e("FROM", remoteMessage.getFrom());

    count++;

    //sendNotification(notification, data);

    setNotificationCount();
}


private void setNotificationCount(AlertList alertList) {
    notificationListener = (NotificationListener) context;
    notificationListener.onNotificationMessage(count);
}

private void sendNotification(RemoteMessage.Notification notification, Map<String, String> data) {
    Bitmap icon = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);

    Intent intent = new Intent(this, AlertOnMap.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    intent.putExtra("AlertDetails", (Serializable) alertList);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);

    NotificationCompat.Builder notificationBuilder = (NotificationCompat.Builder) new NotificationCompat.Builder(this)
            .setContentTitle(notification.getTitle())
            .setContentText(notification.getBody())
            .setAutoCancel(true)
            .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
            .setContentIntent(pendingIntent)
            .setContentInfo(notification.getTitle())
            .setLargeIcon(icon)
            .setColor(Color.RED)
            .setSmallIcon(R.mipmap.ic_launcher);

    try {
        String picture_url = data.get("picture_url");
        if (picture_url != null && !"".equals(picture_url)) {
            URL url = new URL(picture_url);
            Bitmap bigPicture = BitmapFactory.decodeStream(url.openConnection().getInputStream());
            notificationBuilder.setStyle(
                    new NotificationCompat.BigPictureStyle().bigPicture(bigPicture).setSummaryText(notification.getBody())
            );
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(0, notificationBuilder.build());
}

}

創建接口

public interface NotificationListener {

public void onNotificationMessage(AlertList alertList, int i);

}

調用另一個類..喜歡

public class Header extends AppCompatActivity implements NotificationListener{

 /*--------------- OnNotification ----------------------*/

@Override
public void onNotificationMessage(final int count) {

    Log.d("Notification count", "--->   In Header Count = " + count);

}

}

我想在沒有來自另一個類的任何上下文引用的情況下獲取服務中的當前活動上下文。

如果我理解正確,基本上您想將活動的上下文轉換為該活動實現的接口。 問題是:您無法獲得當前活動上下文,因為可能/可能根本沒有當前活動。 有一些上下文可用,但此上下文不能用於您想要的。 讓我解釋一下:

假設用戶一周沒有使用應用程序,他完成了所有活動,退出了應用程序(或操作系統釋放了內存並清理了所有內容)。 服務仍在后台運行,當推送消息到來時,它會根據您的代碼做出反應(假設您想立即顯示通知)。 如果此時您需要上下文,例如通知圖標顏色,您可以使用以下上下文:

int color = ContextCompat.getColor(getApplicationContext(), R.color.colorAccent);

getApplicationContext()將為您提供所需的上下文,但這當然不是活動上下文,因為仍然沒有活動(所有這些都在幾天前完成

希望這個解釋有助於理解這里的概念。 為了更好地理解存在什么樣的上下文,請檢查上下文,什么上下文?

我是通過這種方式做到的

@Override
public void onMessageReceived(final RemoteMessage remoteMessage) {

    if (Manager.getInstance().actualContext != null)
    {
        //Let this be the code in your n'th level thread from main UI thread
        Handler h = new Handler(Looper.getMainLooper());
        h.post(new Runnable() {
            public void run()
            {
                CFAlertDialog.Builder pDialog = new CFAlertDialog.Builder(Manager.getInstance().actualContext)
                        .setDialogStyle(CFAlertDialog.CFAlertStyle.NOTIFICATION)
                        .setTextGravity(Gravity.CENTER)
                        .setMessage(remoteMessage.getNotification().getBody())
                        .setTitle(remoteMessage.getNotification().getTitle());

                pDialog.show();

            }
        });
    }

    super.onMessageReceived(remoteMessage);
}

Manager.getInstance().actualContext 是我的 Manager(單音類)中的一個變量 Context

只是你必須在你所有的活動中實例化

@Override
protected void onResume() {
    super.onResume();
    Manager.getInstance().actualContext = this;
}

並摧毀它

@Override
protected void onDestroy() {
    super.onDestroy();
    Manager.getInstance().actualContext = null;
}

在我的情況下很簡單:

Context.NOTIFICATION_SERVICE to NOTIFICATION_SERVICE

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM