GetTokenTask receive a empty token, please check HmsMessageService.onNewToken receive result - huawei-mobile-services

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.
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:
UPDATE:
I have prepared a simple test case at Github and there the push token is delivered to the onNewToken() method just fine:
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:
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:
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.

We are checking on your issue. Can you help to confirm:
Do you use 3rd Push platform?
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.

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: wwwjamescom#sina.com .

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

Related

I'm using firebase messaging in my flutter app but when I run my project it show Stringtoken=FirebaseInstanceId.getInstance().getToken(senderId, "*");

I'm using firebase messaging in my flutter app but when I run my project it show String token = FirebaseInstanceId.getInstance().getToken(senderId, "*");
when I run my application it shows this error in the console:
C:\Users\cerbi\AppData\Local\Pub\Cache\hosted\pub.dartlang.org\firebase_messaging-9.1.4\android\src\main\java\io\flutter\plugins\firebase\messaging\FlutterFirebaseMessagingPlugin.java:166: error: cannot find symbol
String token = FirebaseInstanceId.getInstance().getToken(senderId, "*");
^
symbol: variable FirebaseInstanceId
location: class FlutterFirebaseMessagingPlugin
Note: Some input files use or override a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
What went wrong:
Execution failed for task ':firebase_messaging:compileDebugJavaWithJavac'.
and when I navigate to the specific file stated in the error message here is the code in there
private Task<Map<String, Object>> getToken(Map<String, Object> arguments) {
return Tasks.call(
cachedThreadPool,
() -> {
String senderId =
arguments.get("senderId") != null
? (String) arguments.get("senderId")
: Metadata.getDefaultSenderId(FirebaseApp.getInstance());
String token = FirebaseInstanceId.getInstance().getToken(senderId, "*");
return new HashMap<String, Object>() {
{
put("token", token);
}
};
});
}
What can I do to resolve this problem, it seems that the existing code is not working anymore
You should use
FirebaseMessaging.getInstance().token
to get token, since
FirebaseInstanceId.getInstance().getToken
is deprecated.
To retrieve the current registration token for an app instance, you need to call
FirebaseMessaging.instance.getToken(); as stated here in their official guide.

IOException in mReferrerClient.getInstallReferrer() with HMS Core version 5.0.1.307

I want to test my own app before going live after integrating with Huawei install Referrer SDK. I followed all the steps found in codelabs and the documentations and when i install the apk on the device , getInstallReferrer method throws IOException. This is my code. What is it that i am doing wrong ?. how can i get installReferrer info for testing purposes ?
Runnable {
referrerClient = newBuilder(context).setTest(true).build()
referrerClient.startConnection(object : InstallReferrerStateListener {
#SuppressLint("SwitchIntDef")
override fun onInstallReferrerSetupFinished(responseCode: Int) {
when (responseCode) {
InstallReferrerClient.InstallReferrerResponse.OK -> {
// Connection established.
try {
val response: ReferrerDetails = referrerClient.installReferrer
val referrerUrl: String = response.installReferrer
val referrerClickTime: Long = response.referrerClickTimestampSeconds
val appInstallTime: Long = response.installBeginTimestampSeconds
}catch (e : IOException){
Log.i("INSTALL_REFERRER","IOException")
}
catch(e: RemoteException){
Log.i("INSTALL_REFERRER","RemoteException")
}
finally {
referrerClient.endConnection()
}
}
InstallReferrerClient.InstallReferrerResponse.FEATURE_NOT_SUPPORTED -> {
Log.i("INSTALL_REFERRER","NOT AVAILABLE")
}
InstallReferrerClient.InstallReferrerResponse.SERVICE_UNAVAILABLE -> {
Log.i("INSTALL_REFERRER","SERVICE UNAVAILABLE")
}
}
}
override fun onInstallReferrerServiceDisconnected() {
Log.i("INSTALL_REFERRER","ReferrerServiceDisconnected")
}
})
}.run()
Please check whether the AIDL interface is added.
Check the screenshot below:
Obtain Install Referrer Information by AIDL
You can call an AIDL API provided by HUAWEI Ads Kit to obtain install referrer information from HUAWEI devices, without integrating any HUAWEI SDK. The install referrer information obtained from a device in either mode (SDK or AIDL) is the same.
Call Process
The Development Procedure is as follows
Create an AIDL file for the IPPSChannelInfoService API and save the file.
Copy the following content to the AIDL file:
package com.huawei.android.hms.ppskit;
/** Important: Do not change the method sequence in the AIDL file. */
interface IPPSChannelInfoService {
String getChannelInfo();
}
Change Build Action to AndroidInterfaceDescription of AIDL file.
Rebuild project.
Create a class to implement Android-native IServiceConnection.
For more details, see docs.
Also, please kindly refer to the demo.
Update:
The package name needs to be specified because setTest(true)
if (this.isTest){
var2 = "com.huawei.pps.hms.test";
}
The empty check on ReferrerDetails can be added.
if (null != referrerDetails && null != mCallback)

org.keycloak.common.VerificationException: Invalid token issuer

I'm developing an Android app, which uses my REST backend. The backend is running on an JBoss instance, which is secured through Keycloak. Since I've updated my Keycloak from 1.0.7 to 2.1.5 I'm experiencing the following problem.
If I try to call a REST API of my backend, JBoss writes the folowing log:
[org.keycloak.adapters.BearerTokenRequestAuthenticator] (default task-39)
Failed to verify token: org.keycloak.common.VerificationException: Invalid token issuer.
Expected 'http://localhost:8180/auth/realms/myrealm', but was 'http://192.168.178.24:8180/auth/realms/myrealm'
at org.keycloak.TokenVerifier.verify(TokenVerifier.java:156)
at org.keycloak.RSATokenVerifier.verify(RSATokenVerifier.java:89)
192.168.178.24 is the right IP address. It seems to be a configuration issue, but where can I config this address?
Has anybody an idea how to fix this problem?
Very simple solution: Make sure when any of your component contact with Keycloak server, they use the same url.
Detailed explanations:
For your case (same as mine), it seems that your Android app is making http request to http://192.168.178.24:8180/... while your server is requesting (or at least configured to) http://192.168.178.24:8180/.... So change your server such that it will request http://192.168.178.24:8180/....
P.S. The exception seems to be the expected behavior to avoid some attacks.
If you take a look into the implementation, here it throws your Exception.
public static class RealmUrlCheck implements Predicate<JsonWebToken> {
private static final RealmUrlCheck NULL_INSTANCE = new RealmUrlCheck(null);
private final String realmUrl;
public RealmUrlCheck(String realmUrl) {
this.realmUrl = realmUrl;
}
#Override
public boolean test(JsonWebToken t) throws VerificationException {
if (this.realmUrl == null) {
throw new VerificationException("Realm URL not set");
}
if (! this.realmUrl.equals(t.getIssuer())) {
throw new VerificationException("Invalid token issuer. Expected '" + this.realmUrl + "', but was '" + t.getIssuer() + "'");
}
return true;
}
};
I think your Client configuration is not correct. Do you have the same clients as in your Keycloak?

Can't use cache:true with OAuth.initialize

I am trying to use OAuth according to https://oauth.io/docs/api in an android eclipse app.
import io.oauth.*;
.....
final OAuth o = new OAuth(this);
o.initialize(KEY);
works fine.
However, I want to use the cache functionality in order not to log on every time, so I try
o.initialize(KEY, {cache: true});
Unfortunately this won't compile. I get
"Multiple markers at this line
-Syntax error on tokens, delete these tokens
-Syntax error on token(s), misplaced construct(s)"
As you can tell I am an android and Eclipse newbie, any help appreciated.
The public key is the only argument used for the initialize method.
The correct method that accepts the cache object as an argument is popup.
Example:
OAuth.initialize('x9x9x9x9x9'); //OAuth.io public key
var promise = OAuth.popup('google_mail', {cache: true});
promise.done(function (result) {
    // make API calls
});
promise.fail(function (error) {
    // handle errors
});

BlackBerry - Facebook extended permissions

I've just found a great sample of Facebook Connect on Blackberry by Eki Y. Baskoro,
The following is a short HOWTO on using Facebook Connect on Blackberry. I created a simple Facade encapsulating the Facebook REST API as well as added 'rough' MVC approach for screen navigation. I have tested on JDE 4.5 using 8320 simulator. This is still work in progress and all work is GPLed.
It works great for reading stuff.
NB Don't forget to get Facebook App Key and set it in TestBB class.
But now I want to post something on my wall. So I've add new method to FacebookFacade class using Stream.publish API:
/***
* Publishes message to the stream.
* #param message - message that will appear on the facebook stream
* #param targetId - The ID of the user, Page, group, or event where
* you are publishing the content.
*/
public void streamPublish(String message, String targetId)
{
Hashtable arguments = new Hashtable();
arguments.put("method", "stream.publish");
arguments.put("message", message);
arguments.put("target_id", targetId);
try {
JSONObject result = new JSONObject(
int new JSONTokener(sendRequest(arguments)));
int errorCode = result.getInt("error_code");
if (errorCode != 0) System.out.println("Error Code: "+errorCode);
} catch (Exception e) {
System.out.println(e);
}
}
/***
* Publishes message on current user wall.
* #param message - message that will appear on the facebook stream
*/
public void postOnTheWall(String message)
{
String targetId = String.valueOf(getLoggedInUserId());
streamPublish(message, targetId);
}
This will return Error code 200, "The user hasn't authorized the application to perform this action"
First I thought it's related with Facebook -> Application Settings -> Additional Permissions -> Publish recent activity (one line stories) to my wall but even checked, no difference...
Then I've found this post explains that issue related with extended permissions.
This in turn should be fixed by modifying url a little in LoginScreen class :
public LoginScreen(FacebookFacade facebookFacade) {
this.facebookFacade = facebookFacade;
StringBuffer data = new StringBuffer();
data.append("api_key=" + facebookFacade.getApplicationKey());
data.append("&connect_display=popup");
data.append("&v=1.0");
//revomed
//data.append("&next=http://www.facebook.com/connect/login_success.html");
//added
data.append("&next=http://www.facebook.com/connect/prompt_permissions.php?" +
"api_key="+facebookFacade.getApplicationKey()+"&display=popup&v=1.0"+
"&next=http://www.facebook.com/connect/login_success.html?"+
"xxRESULTTOKENxx&fbconnect=true" +
"&ext_perm=read_stream,publish_stream,offline_access");
data.append("&cancel_url=http://www.facebook.com/connect/login_failure.html");
data.append("&fbconnect=true");
data.append("&return_session=true");
(new FetchThread("http://m.facebook.com/login.php?"
+ data.toString())).start();
}
Unfortunately it's not working. Still Error Code 200 in return to stream.publish request...
Do you have any suggestions how to resolve this?
Thank you!
I have posted the updated API on my website (http://www.baskoro.web.id/facebook-connect-blackberry-HOWTO.html) and this should solve this issue. Please let me know otherwise.
Salam. Cheers!
Eki