我正在尝试实现 OneSignal Android sdk。一切都很好,除了获取userId
OneSignal 文档,这里有文档。步骤是:
defaultConfig {
applicationId "com.nuspay.onesignaldemo"
manifestPlaceholders = [manifestApplicationId: "${applicationId}",
onesignal_app_id: "OPEN_SIGNAL_ID",
onesignal_google_project_number: "GOOGLE_PLAY_PROJECT_NUMBER"]
minSdkVersion 17
targetSdkVersion 23
versionCode 1
versionName "1.0"
}
并将这个 gradle 文件添加为依赖项:
compile 'com.onesignal:OneSignal:2.+@aar'
compile 'com.google.android.gms:play-services-gcm:+'
compile 'com.google.android.gms:play-services-analytics:+'
compile "com.google.android.gms:play-services-location:+"
在 menifest.xml 添加 Application 类和此权限
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
应用程序类是这样的:
public class DemoApplication extends Application{
public static final String TAG = DemoApplication.class.getSimpleName();
private static DemoApplication instace;
@Override
public void onCreate() {
super.onCreate();
instace=this;
initialization();
}
private void initialization() {
OneSignal.startInit(this)
.setAutoPromptLocation(true)
.setNotificationOpenedHandler(new ExampleNotificationOpenedHandler()).
init();
OneSignal.idsAvailable(new OneSignal.IdsAvailableHandler() {
@Override
public void idsAvailable(String userId, String registrationId) {
Log.d("debug", "User:" + userId);
if (registrationId != null)
Log.d("debug", "registrationId:" + registrationId);
}
});
OneSignal.enableNotificationsWhenActive(true);
OneSignal.enableInAppAlertNotification(true);
OneSignal.promptLocation();
}
}
ExampleNotificationOpenedHandler
是这样的:
public class ExampleNotificationOpenedHandler implements OneSignal.NotificationOpenedHandler {
@Override
public void notificationOpened(String message, JSONObject additionalData, boolean isActive) {
try {
Log.d("HWT","Message-->"+message);
Log.d("HWT","additionalData-->"+additionalData);
Log.d("HWT","isActive-->"+isActive);
if (additionalData != null) {
if (additionalData.has("actionSelected"))
Log.d("HWT", "OneSignal notification button with id " + additionalData.getString("actionSelected") + " pressed");
Log.d("OneSignalExample", "Full additionalData:\n" + additionalData.toString());
}
} catch (Throwable t) {
t.printStackTrace();
}
}
}
现在在我的Activity
onCreate
回调中使用下面的代码来获取 userId。
OneSignal.idsAvailable(new OneSignal.IdsAvailableHandler() {
@Override
public void idsAvailable(String userId, String registrationId) {
String text = "OneSignal UserID:\n" + userId + "\n\n";
}
});
我的问题idsAvailable
是永远不会调用回调。
笔记:
- 我设置GCM权限,获取项目号,设置打开信号项目都ok
你能找出我的缺点吗?提前致谢。