When the user accepts push notification permissions, they will not instantly have a user ID. When the user accepts push notification permissions, the SDK sends out an HTTP request to register with OneSignal's server. Once that request is finished, the user subscription state is updated with a user ID.
I would suggest using the OSSubscriptionStateObserver protocol in order to get updated whenever the subscription state changes. You can access the user ID there.
public class MainActivity extends Activity implements OSSubscriptionObserver {
protected void onCreate(Bundle savedInstanceState) {
OneSignal.addSubscriptionObserver(this);
}
public void onOSSubscriptionChanged(OSSubscriptionStateChanges stateChanges) {
if (!stateChanges.getFrom().isSubscribed() &&
stateChanges.getTo().isSubscribed()) {
new AlertDialog.Builder(this)
.setMessage("You've successfully subscribed to push notifications!")
.show();
// get player ID
stateChanges.getTo().getUserId();
}
Log.i("Debug", "onOSPermissionChanged: " + stateChanges);
}
}
From Onesignal library 4+ version there is a small tweak to this method.
public class MainActivity extends Activity implements OSSubscriptionObserver {
protected void onCreate(Bundle savedInstanceState) {
OneSignal.addSubscriptionObserver(this);
}
public void onOSSubscriptionChanged(OSSubscriptionStateChanges stateChanges) {
if (!stateChanges.getFrom().getSubscribed() &&
stateChanges.getTo().getSubscribed()) {
new AlertDialog.Builder(this)
.setMessage("You've successfully subscribed to push notifications!")
.show();
// get player ID
stateChanges.getTo().getUserId();
}
Log.i("Debug", "onOSSubscriptionChanged: " + stateChanges);
}
}
/*
Example Logcat entry - User disabling notifications then returning to your app.
onOSSubscriptionChanged:
{"from":{"pushToken":"APA91bG9cmZ262s5gJhr8jvbg1q7aiviEC6lcOCgAQliEzHKO3eOdX5cm7IQqMSWfy8Od7Ol3jSjFfvCfeO2UYUpanJCURJ8RdhgEuV8grYxOCwPNJr5GoqcWTQOaL9u-qE2PQcFlv4K","userSubscriptionSetting":true,"subscribed":false},
"to": {"userId":"22712a53-9b5c-4eab-a828-f18f81167fef","pushToken":"APA91bG9cmZ262s5gJhr8jvbg1q7aiviEC6lcOCgAQliEzHKO3eOdX5cm7IQqMSWfy8Od7Ol3jSjFfvCfeO2UYUpanJCURJ8RdhgEuV8grYxOCwPNJr5GoqcWTQOaL9u-qE2PQcFlv4K","userSubscriptionSetting":true,"subscribed":true}}