我正在尝试在收到新通知时打开一个片段。为此,我使用BroadcastReceiver。问题是我没有在sendNotification
类FirebaseMessagingService
类中的onCreate
方法的活动中收到消息。我认为问题是我在// Globally declared
private IntentFilter mIntentFilter;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
// Open a fragment automatically
if (findViewById(R.id.frame) != null) {
if (savedInstanceState != null) {
return;
}
myFragmentManager = getSupportFragmentManager();
myFragmentTransaction = myFragmentManager.beginTransaction();
myFragmentTransaction.replace(R.id.frame, new ProdList()).commit();
}
mIntentFilter = new IntentFilter();
mIntentFilter.addAction("com.sam.CUSTOM_INTENT");
}
@Override
protected void onResume() {
super.onResume();
registerReceiver(mReceiver, mIntentFilter);
}
@Override
protected void onPause() {
super.onPause();
unregisterReceiver(mReceiver);
}
private BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("com.sam.CUSTOM_INTENT")) {
Toast.makeText(getApplicationContext(), "GOT MESSAGE", Toast.LENGTH_SHORT).show();
InventoryList il = new InventoryList();
replaceFragment(il,"IL");
}
}
};
内声明了IntentFilter,当我点击推送通知时它没有被调用。还有其他办法吗?
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
if (remoteMessage.getData().size() > 0) {
for (Map.Entry<String, String> entry : remoteMessage.getData().entrySet()) {
String value = entry.getValue();
try {
JSONObject obj = new JSONObject(value);
sendNotification(obj.getString("message"),"SUCCESS");
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
private void sendNotification(String messageBody, String param) {
Intent intent = new Intent(this, HomeActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
intent.setAction("MESSAGE");
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_com.sam.CUSTOM_INTENTr)
.setContentTitle("Nika")
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notificationBuilder.build());
}
{{1}}
答案 0 :(得分:1)
如果您希望BroadcastReceiver获取广播,您必须实际发送广播。将此代码放入onMessageReceived()
:
Intent intent = new Intent("com.sam.CUSTOM_INTENT");
context.sendBroadcast(intent);
此代码段将使用IntentFilter匹配操作"com.sam.CUSTOM_INTENT"
将广播发送到所有已注册的BroadcastReceivers。
因此,对于当前的实现,您的活动将在恢复时进行广播。