java如何在安卓中使用FCM向单个设备发送数据消息
我不太会使用Firebase cloud messaging
,希望向单个设备发送带有数据的消息或通知。我已经向所有设备发送了通知,但不知道如何将其发送到单个目标设备。我浏览了很多网站和教程,但都没找到
根据我正在学习的一个教程,我在我的
主要活动。java:
package in.w3dev.fcm2;
import 安卓.support.annotation.NonNull;
import 安卓.support.v7.app.AppCompatActivity;
import 安卓.os.Bundle;
import 安卓.util.Log;
import com.google.firebase.iid.FirebaseInstanceId;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FirebaseInstanceId.getInstance().getInstanceId()
.addOnCompleteListener(new OnCompleteListener<InstanceIdResult>() {
@Override
public void onComplete(@NonNull Task<InstanceIdResult> task) {
if (!task.isSuccessful()) {
return;
}
String token = task.getResult().getToken();
String msg = getString(R.string.fcm_token, token);
Log.d(TAG, msg);
}
});
}
}
但它显示了error : can't resolve symbol getInstanceId(), InstanceResultId
。
由于某种原因,所有粗体字的问题都没有得到解决。我已经按照安卓 studio右侧FCM窗口中的描述,创建了正确扩展FirebaseInstanceIdService
和FirebaseMessagingService
的服务。
告诉我如何解决这些错误,或者使用FCM向单个设备发送消息的其他方法
此外,是否可能因为我的应用程序中运行的firebase的早期版本而无法导入InstanceResultId
类
我试图升级这个版本,但它再次显示了一系列错误,所以我只保留了11.0.4
以下是应用程序文件夹中的Gradle文件:
apply plugin: 'com.安卓.application'
安卓 {
compileSdkVersion 26
defaultConfig {
applicationId "in.w3dev.fcm2"
minSdkVersion 19
targetSdkVersion 26
versionCode 1
versionName "1.0"
testInstrumentationRunner "安卓.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-安卓.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.安卓.support:appcompat-v7:26.1.0'
implementation 'com.安卓.support.constraint:constraint-layout:1.1.3'
implementation 'com.google.firebase:firebase-messaging:20.1.0'
testImplementation 'junit:junit:4.12'
安卓TestImplementation 'com.安卓.support.test:runner:1.0.2'
安卓TestImplementation 'com.安卓.support.test.espresso:espresso-core:3.0.2'
implementation 'com.squareup.okhttp3:okhttp:3.10.0'
}
apply plugin: 'com.google.gms.google-services'
# 1 楼答案
要向特定设备发送推送通知,后端服务器需要存储设备令牌并向该令牌发送通知
您可以检索当前设备令牌并发送到服务器,如下所示
然后,服务器将向该设备发送推送通知
请记住,您不能使用firebase控制台将noti直接发送到特定设备,因为它没有用于此的UI控件。但你可以用邮递员来测试
# 2 楼答案
更新:我解决了这个问题。我将android studio更新为最新版本,同时更新了gradle和所有其他东西,并添加了最新的firebase版本依赖项,代码运行良好