我的代碼集成FCM .. 我想獲得當前的活動上下文推送到達時。 用於通過上下文投送監聽器的目的。在Android中如何在擴展FirebaseMessagingService時調用onMessageReceived獲取當前的Activity上下文?
片段代碼在這裏...
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);
}
調用另一個class..like
public class Header extends AppCompatActivity implements NotificationListener{
/*--------------- OnNotification ----------------------*/
@Override
public void onNotificationMessage(final int count) {
Log.d("Notification count", "---> In Header Count = " + count);
}
}
我想在沒有任何其他類的上下文引用的情況下獲取當前活動上下文。
通常標誌着一個答案。新年快樂:) – Ewoks