Android FCM(Firebase Cloud Messaging)是一种用于发送推送通知的服务。在使用过程中,可能会遇到一些常见的问题。下面是一些常见问题以及解决方法,包含一些代码示例:
public class MyFirebaseMessagingService extends FirebaseMessagingService {
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
// 处理接收到的推送通知
String title = remoteMessage.getNotification().getTitle();
String body = remoteMessage.getNotification().getBody();
// 显示通知
showNotification(title, body);
}
private void showNotification(String title, String body) {
// 创建并显示通知
NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
.setContentTitle(title)
.setContentText(body)
.setSmallIcon(R.drawable.ic_notification);
NotificationManagerCompat managerCompat = NotificationManagerCompat.from(this);
managerCompat.notify(0, builder.build());
}
}
public class MyFirebaseMessagingService extends FirebaseMessagingService {
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
// 处理接收到的推送通知
String title = remoteMessage.getNotification().getTitle();
String body = remoteMessage.getNotification().getBody();
// 设置点击通知时的操作
Intent intent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
// 显示通知
showNotification(title, body, pendingIntent);
}
private void showNotification(String title, String body, PendingIntent pendingIntent) {
// 创建并显示通知
NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
.setContentTitle(title)
.setContentText(body)
.setSmallIcon(R.drawable.ic_notification)
.setContentIntent(pendingIntent)
.setAutoCancel(true);
NotificationManagerCompat managerCompat = NotificationManagerCompat.from(this);
managerCompat.notify(0, builder.build());
}
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 处理点击通知的操作
if (getIntent().getExtras() != null) {
String data = getIntent().getStringExtra("data");