GetTokenTask receive a empty token, please check HmsMessageService.onNewToken receive result

1k views Asked by At

My word game published at Huawei AppGallery uses Account and Push Kits:

implementation 'com.huawei.hms:hwid:6.4.0.300'
implementation 'com.huawei.hms:push:6.3.0.302'

The Account Kit works well and I am able to obtain the open id and display name of the phone user.

This means, that the SHA-256 certificate fingerprints are configured properly and are not causing the problem with Push Kit described below.

AppGallery Connect

The problem: the push token is not obtainable on an EMUI 9.1 phone (see screenshot at the very bottom).

AndroidManifest.xml:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />

<application>
    <service
        android:name="de.afarber.HmsService"
        android:exported="false">
        <intent-filter>
            <action android:name="com.huawei.push.action.MESSAGING_EVENT" />
        </intent-filter>
    </service>
</application>

HmsService.java:

public class HmsService extends HmsMessageService {
    @Override
    public void onNewToken(String token) {   // THIS IS NEVER CALLED !!!
        super.onNewToken(token);
        Log.d(Utils.TAG,"onNewToken token=" + token);
    }
}

My custom Application class:

private final ScheduledExecutorService mExecutor = Executors.newSingleThreadScheduledExecutor();

@Override
public void onCreate(@NonNull Context context) {
    HmsMessaging.getInstance(this).setAutoInitEnabled(true);

    mExecutor.execute(() -> {
        try {
            String appId = context.getString(R.string.huawei_app_id); // VALUE IN DEBUGGER: "102776361"
            String token = HmsInstanceId.getInstance(context).getToken(appId, "HCM"); // ALWAYS EMPTY
            if (!TextUtils.isEmpty(token)) {
                // this only supposed to work for EMUI 10 or newer
                Log.d(Utils.TAG,"getToken token=" + token);
            }
        } catch (Exception ex) {
            Log.w(TAG,"getToken failed", ex);
        }
    });
}

When I debug the app at my Huawei ANE-LX1 phone I see in the logcat:

I/HMSSDK_HMSPackageManager: <initHmsPackageInfoForMultiService> Succeed to find HMS apk: com.huawei.hwid version: 60400311
...
I/HMSSDK_PendingResultImpl: init uri:push.gettoken
...
I/HMSSDK_HmsClient: post msg api_name:push.gettoken, app_id:102776361|, pkg_name:com.wordsbyfarber.huawei, sdk_version:60400300, session_id:*, transaction_id:102776361ttoken20220330184241694787985, kitSdkVersion:60300301, apiLevel:1
I/HMSSDK_BaseAdapter: In constructor, activityWeakReference is java.lang.ref.WeakReference@343238b, activity is de.afarber.MainActivity@50109d0
I/HMSSDK_BaseAdapter: in baseRequest + uri is :push.gettoken, transactionId is : 102776361ttoken20220330184241694787985
I/HMSSDK_PendingResultImpl: init uri:push.gettoken
I/HMSSDK_PendingResultImpl: setResultCallback
I/HMSSDK_PendingResultImpl: setResult:0
...
I/HMSSDK_BaseAdapter: baseCallBack.onComplete
I/HMSSDK_HmsClient: receive msg status_code:0, error_code:0, api_name:push.gettoken, app_id:102776361|, pkg_name:com.wordsbyfarber.huawei, session_id:*, transaction_id:102776361ttoken20220330184241642989857, resolution:null
I/HMSSDK_TaskApiCall: doExecute, uri:push.gettoken, errorCode:0, transactionId:102776361ttoken20220330184241642989857
I/HMSSDK_HmsInstanceId: GetTokenTask receive a empty token, please check HmsMessageService.onNewToken receive result.
I/HMSSDK_HMSPackageManager: Enter getHMSPackageNameForMultiService
I/HMSSDK_RequestManager: removeReqByTransId
I/HMSSDK_BaseAdapter: api is: push.gettoken, resolution: null, status_code: 0
I/HMSSDK_BaseAdapter: baseCallBack.onComplete
I/HMSSDK_HmsClient: receive msg status_code:0, error_code:0, api_name:push.gettoken, app_id:102776361|, pkg_name:com.wordsbyfarber.huawei, session_id:*, transaction_id:102776361ttoken20220330184241694787985, resolution:null
I/HMSSDK_TaskApiCall: doExecute, uri:push.gettoken, errorCode:0, transactionId:102776361ttoken20220330184241694787985
I/HMSSDK_HmsInstanceId: GetTokenTask receive a empty token, please check HmsMessageService.onNewToken receive result.
I/HMSSDK_HMSPackageManager: Enter getHMSPackageNameForMultiService
I/HMSSDK_RequestManager: removeReqByTransId
I/HMSSDK_AutoInit: Push init succeed

And by setting debugger breakpoints and inspecting logcat for my logs I see that:

  • I call getToken() and pass it my app id "102776361"
  • The getToken() takes some time and then returns an empty token (which is expected for EMUI 9.x)
  • However the HmsService method onNewToken() is never called (which is NOT OK)

I have unsuccessfully tried multiple things to resolve my issue -

  • Tried adding following meta data to the AndroidManifest.xml:

  • Tried obtaining AAID manually in onCreate (obtaining AAID works OK, but token is still not delivered):

      HmsInstanceId.getInstance(context).getAAID()
              .addOnSuccessListener(aaidResult -> Log.d(TAG, "getAAID aaid=" + aaidResult.getId()))
              .addOnFailureListener(ex -> Log.w(TAG, "getAAID failed", ex));
    
  • Tried adding more permissions to the AndroidManifest.xml:

android.permission.READ_PHONE_STATE
android.permission.ACCESS_NETWORK_STATE
android.permission.ACCESS_WIFI_STATE
android.permission.WRITE_EXTERNAL_STORAGE
android.permission.REQUEST_INSTALL_PACKAGES
  • Tried exporting HmsService in the AndroidManifest.xml (this is not recommended according to @shirley!):

      <service
          android:name="de.afarber.HmsService"
          android:enabled="true"
          android:exported="true"
          android:permission="${applicationId}.permission.PROCESS_PUSH_MSG"
          android:process=":HmsMessageService">
          <intent-filter>
              <action android:name="com.huawei.push.action.MESSAGING_EVENT" />
          </intent-filter>
      </service>
    
  • Tried overriding public void onNewToken(String token, Bundle bundle) in HmsService.java

My EMUI 9.1 phone is up to date and I am located in Germany:

EMUI screenshot

UPDATE:

I have prepared a simple test case at Github and there the push token is delivered to the onNewToken() method just fine:

app screenshot

After adding onCreate() to the both custom HmsMessageService classes I have noticed that the method is called in the test app, but not in my real app.

Unfortunately, I have not found the reason for that yet... Here a screenshot of the merged AndroidManifest.xml:

AndroidManifest screenshot

I have tried starting the service by running the following line in the onCreate() method of my custom Application class:

startService(new Intent(this, de.afarber.HmsService.class));

And the line does not fail and I can see the onCreate() method of the HmsService being run. However the onNewToken() method is still not called. I wonder if some additional registration is needed in the HMS Core Android code after starting the service "manually".

UPDATE 2:

After rechecking all settings and I have noticed, that I didn't enable HUAWEI Push Kit in the AppGallery Connect:

AppGallery Connect

After enabling that setting I am able to receive push token on my Huawei Phone.

And after auto-updating I am even receiving a push token on a non-Huawei phone: Moto G Play.

3

There are 3 answers

6
zhangxaochen On BEST ANSWER

We are checking on your issue. Can you help to confirm:

  1. Do you use 3rd Push platform?
  2. How many classes you have which extends HmsMessageService?

Don't config the following items: android:permission="${applicationId}.permission.PROCESS_PUSH_MSG" android:process=":HmsMessageService"

After the confirmation above, you can share more log to me.

2
coollei On

You can collect the log with this command: "adb logcat -v time > D:\hwpush.log". In addition, you can search the file "push.log" in file manager, and share it here: [email protected] .

0
Zinna On

Here a quick check list

Make sure the push kit is enable for your app

Make sure the correct agconnect-services.json is copy to the app directory. If you have more than one copy

You can use the Push kit console to test sending notification to your app to verify that your setting is corrected

You can use the automatic initialization to test if you can receive the push token.

Here the link to document https://developer.huawei.com/consumer/en/doc/development/HMSCore-Guides/android-client-dev-0000001050042041#section13546121751811

Here is the snippet of my code that received the token just fine.

in the MainActivity

public class MainActivity extends AppCompatActivity implements OSSubscriptionObserver {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

   
   
        setAutoInitEnabled(true);
    }
   private void setAutoInitEnabled(final boolean isEnable) {
        if(isEnable){
            // Enable automatic initialization.
            HmsMessaging.getInstance(this).setAutoInitEnabled(true);
        } else {
            // Disable automatic initialization.
            HmsMessaging.getInstance(this).setAutoInitEnabled(false);
        }
    }
}

in the class that response to the HMS messaging service

public class MyHMSService  extends HmsMessageService {

/\*\*
 \* When an app calls the getToken method to apply for a token from the server,
 \* if the server does not return the token during current method calling,
 \* the server can return the token through this method later.
 \* This method callback must be completed in 10 seconds.
 \* Otherwise, you need to start a new Job for callback processing.
 \*
 \* @param token token
 \* @param bundle bundle
 \*/
@Override
public void onNewToken(String token, Bundle bundle) {

    Toast.makeText(getApplicationContext(), "token value is: " + token, Toast.LENGTH_SHORT).show();
}

In case you still have the problem of receiving the message, please try a sample code and send a message from

AGC.developer.huawei.com/consumer/en/doc/development/…