GetTokenTask收到空token,请检查HmsMessageService.onNewToken接收结果

发布于 2025-01-18 01:12:55 字数 7408 浏览 0 评论 0 原文

我在

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

。而且我能够获得电话用户的打开ID和显示名称。

这意味着, SHA-256证书指纹配置正确,并且不会引起以下推动套件的问题。

问题:在EMUI 9.1手机上无法获得推动令牌(请参阅最底部的屏幕截图)。

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

通过设置调试器断点并检查logcat中的日志,我会看到:

  • 我致电getToken()并传递我的应用程序ID“ 102776361” getToken
  • ()getToken()需要一些时间,然后返回一个空的令牌(EMUI可以预期EMUI 9.x)
  • 然而,从未调用HMSService方法OnNewToken()(这不行),

我未能成功尝试多个解决我的问题 -

  • 尝试在AndroidManifest中添加以下元数据。 XML:

  • 尝试在ongreate中手动获取AAID(获取AAID可以正常工作,但仍未交付令牌):

      hmsinstanceId.getInstance(context).getAaid()
              .addonSuccessListener(aaidResult -&gt; log.d(tag,“ getaaid aaid =” + aaidResult.getID()))))
              。
     
  • 尝试在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
 
  • 尝试在AndroidManifest.xml中导出HMSService(根据@shirley不建议这样做!):

     &lt;服务
          android:name =“ de.afarber.hmsservice”
          Android:enabled =“ true”
          Android:导出=“ true”
          android:clermission =“ $ {applicationid} .permission.process_push_msg”
          Android:process =“:hmsmessageservice”&gt;
          &lt; intent-filter&gt;
              &lt; Action Android:name =“ com.huawei.push.action.messaging_event” /&gt;
          &lt;/intent-filter&gt;
      &lt;/service&gt;
     
  • 尝试覆盖 public void onnewtoken(string token,bundle bundle bundle bundle bundle) hmssservice.java.java

我的emui 9.1电话是最新的,我位于德国:

​/strong>

我已经准备了 github 的简单测试案例推送令牌已交付到 onnewtoken()方法可以很好:

=“ https://i.sstatic.net/pc4ce.jpg” Alt =“ App ScreenShot”>

在将 oncreate()添加到两个自定义HMSMESSAGESEVICE类中后方法是在测试应用中调用的,但在我的真实应用程序中却没有。

不幸的是,我还没有找到原因...在这里,合并后的androidManifest.xml的屏幕截图:

我尝试通过在我自定义的otCreate()方法中运行以下行来启动服务,应用程序类:

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

并且该行不会失败,我可以看到 increate() HMSService 正在运行的方法。但是,仍然未调用 onNewToken()方法。我想知道在“手动”启动服务后,HMS核心Android代码中是否需要一些其他注册。

更新2:

重新检查所有设置后,我注意到,我没有在 appgallery connect

“

启用该设置后,我能够在我的huawei手机上接收推送令牌。

自动更新后,我什至在非武器手机上得到推动令牌:Moto G Play。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

清欢 2025-01-25 01:12:55

我们正在检查您的问题。您能帮助确认:

  1. 您使用第三推平台吗?
  2. 您有多少个班级扩展了HMSMESSAGESERVICE?

不要配置以下项目:
android:clermission =“ $ {applicationid} .permission.process_push_msg”
Android:Process =“:HMSMESSAGESERVICE”,

在上述确认后,您可以向我分享更多日志。

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.

漆黑的白昼 2025-01-25 01:12:55

您可以使用以下命令收集日志:“adb logcat -v time > D:\hwpush.log”。
另外,您可以在文件管理器中搜索“push.log”文件,并在此处共享:[电子邮件受保护]

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] .

后知后觉 2025-01-25 01:12:55

这里是一个快速检查列表

确保您的应用程序启用了推送工具包

确保将正确的 agconnect-services.json 复制到应用程序目录。如果您有多个副本

您可以使用推送套件控制台测试向您的应用程序发送通知,以验证您的设置是否正确

您可以使用自动初始化来测试是否可以接收推送令牌。

这里是文档的链接 https://developer.huawei.com/consumer/en/doc/development/HMSCore-Guides/android-client-dev-0000001050042041#section13546121751811

这是我刚刚收到令牌的代码片段美好的。

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);
        }
    }
}

在响应HMS消息服务的类中的

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();
}

如果您仍然遇到消息接收问题,请尝试示例代码并从

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

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/…

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文