为解决这个问题,可以使用以下代码示例,在应用程序中使用推送通知。
1、首先,确保已经在应用程序中添加了以下依赖项:
dependencies { implementation 'com.google.firebase:firebase-messaging:11.0.4' }
2、在AndroidManifest.xml文件中,添加以下权限:
3、在应用程序中,创建一个名为MyFirebaseMessagingService.java的服务:
import com.google.firebase.messaging.FirebaseMessagingService; import com.google.firebase.messaging.RemoteMessage;
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "MyFirebaseMsgService";
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Log.d(TAG, "From: " + remoteMessage.getFrom());
if (remoteMessage.getData().size() > 0) {
Log.d(TAG, "Message data payload: " + remoteMessage.getData());
}
if (remoteMessage.getNotification() != null) {
Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
}
}
@Override
public void onNewToken(String token) {
Log.d(TAG, "Refreshed token: " + token);
}
}
4、在应用程序的MainActivity.java中,启动MyFirebaseMessagingService服务:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent(this, MyFirebaseMessagingService.class);
startService(intent);
}
}
5、在Firebase控制台中,创建一个新的Firebase项目,并将JSON文件下载到应用程序中。在应用程序中的build.gradle文件中,添加以下代码:
apply plugin: 'com.google.gms.google-services'
dependencies { classpath 'com.google.gms:google-services:4.3.5' }
6、在应用程序的build.gradle文件中,添加以下依赖项:
dependencies { // Other dependencies implementation platform('com.google.firebase:firebase-bom:26.7.0