在Android中如何在扩展FirebaseMessagingService调用onMessageReceived时获取当前的Activity上下文?

时间:2016-09-13 09:21:50

标签: android service interface android-context firebase-cloud-messaging

我的整合FCM代码.. 我希望在推送到达时获得当前的活动上下文。 用于使用上下文来转换侦听器的目的。

此处代码段代码...

<script type="text/javascript">
function showStuff(id, btn) {
    document.getElementById("A").style.display = 'none';
    document.getElementById("B").style.display = 'none';
    if (id == "A") {
        document.getElementById("A").style.display = 'block';
    } else {
        document.getElementById("B").style.display = 'block';
    }

}
</script>  

}

创建了界面

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);

}

我想在没有来自另一个类的任何上下文引用的情况下获取当前活动上下文。

3 个答案:

答案 0 :(得分:7)

如果我理解正确,基本上你想将活动的上下文转换为该活动实现的接口。问题是:您无法获取当前活动上下文,因为可能/可能根本没有当前活动。有一些上下文可用,但此上下文不能用于您想要的内容。让我解释一下:

假设用户没有使用app一周,他完成了所有活动,退出应用程序(或OS释放内存并清理所有内容)。服务仍在后台运行,当推送消息到来时,它会根据您的代码做出反应(假设您立即想要显示通知)。如果此时需要上下文,例如通知图标颜色,则可以使用以下上下文:

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

getApplicationContext()会为您提供所需的上下文,但这当然不是活动上下文,因为仍然没有活动(所有这些都是在几天前完成的

希望这个解释有助于理解这里的概念。 为了更好地理解存在什么样的上下文,请检查Context, What Context?

答案 1 :(得分:1)

我是这样做的

@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(Singletone类)中的变量Context

只需要在所有活动中加以实例

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

并摧毁它

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

答案 2 :(得分:0)

就我而言很简单:

Context.NOTIFICATION_SERVICE to NOTIFICATION_SERVICE