Using SMS Retriever API with Instant Apps - android

I have a functioning instant app and I've successfully incorporated the SMS Retriever API in several apps, but the two don't seem to function together. Is there a way to make them function together, or does there exist documentation about this not being supported?
public class SmsClient {
private SmsReceiver smsReceiver;
public interface GoogleTaskListener extends OnSuccessListener<Void>, OnFailureListener {
}
public SmsClient(#NonNull VerificationCodeListener verificationCodeListener,
int codeLength) {
this.smsReceiver = new SmsReceiver(verificationCodeListener, codeLength);
}
public void attach(Context context) {
SmsRetrieverClient client = SmsRetriever.getClient(context);
Task<Void> startSmsReceiverTask = client.startSmsRetriever();
GoogleTaskListener googleTaskListener = new GoogleTaskListener() {
#Override
public void onSuccess(Void v) {
Timber.i("Sms task succeeded!");
}
#Override
public void onFailure(#NonNull Exception e) {
Timber.e("Sms task failed."); //Message "17: API: SmsRetriever.API is not available on this device."
}
};
startSmsReceiverTask.addOnSuccessListener(googleTaskListener);
startSmsReceiverTask.addOnFailureListener(googleTaskListener);
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(SmsRetriever.SMS_RETRIEVED_ACTION);
context.registerReceiver(smsReceiver, intentFilter);
}
public void detach(Context context) {
context.unregisterReceiver(smsReceiver);
}
}
When starting the SMS Retriever with startSmsRetriever() in a regular app, onSuccess is called.
When attempting to start the SMS Retriever in the same application run as an Instant App, onFailure is called with the error message 17: API: SmsRetriever.API is not available on this device.
Ultimately, we're hoping to have a one-time-password delivered by SMS automatically processed by a running instant app to verify a session. Any information on the subject would be helpful.
I'm currently running this in the Pixel 3 (API 28) emulator.

As TWL commented, it does work. It just doesn't work in the emulator.

Related

SMS Retriever API not working in emulator

#Override
public void startClient(final Callback callback) {
SmsRetrieverClient client = SmsRetriever.getClient(context);
client.startSmsRetriever();
Task<Void> task = client.startSmsRetriever();
task.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
callback.onSuccess();
}
});
task.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
callback.onFail(e);
}
});
}
The code above is the suggested way Google encourages to use their SMS Reytriever API. This method is meant to start a client before the BroadcastReceiver looks for incoming sms messages. The problem here is that onSuccess and onFailure are never called, none of them, and only happens with a Android emulators. I put some breakpoints and logs to confirmed this, the client never notifies back what happened.
This is not a hash problem since this is only related to the initialization of the SmsRetrieverClient.
I'm really confused and don't know what's happening. To never notify a listener is a behaviour nobody would expect, I'm even thinking that this problem might be related to other factors since I recenlty formatted my computer and re-installed latest Android Studio, because before that this code was working on both emulators and physical devices.
Try removing the redundant client.startSmsRetriever(); in the second line.
Make sure the play services version on your emulator/device is > 10.2.0
You can check the play services version using -
private static final String MIN_SUPPORTED_PLAY_SERVICES_VERSION = "10.2";
public static boolean isSmsRetrieverApiAvailable(Context context) {
if (!isPlayServicesAvailable(context)) {
return false;
}
try {
String playServicesVersionName = context.getPackageManager().getPackageInfo(GoogleApiAvailability.GOOGLE_PLAY_SERVICES_PACKAGE, 0).versionName; // should be >10.2.0
return playServicesVersionName.compareTo(MIN_SUPPORTED_PLAY_SERVICES_VERSION) > 0;
} catch (PackageManager.NameNotFoundException e) {
return false;
}
}
private static boolean isPlayServicesAvailable(Context context) {
GoogleApiAvailability googleApiAvailability = GoogleApiAvailability.getInstance();
int resultCode = googleApiAvailability.isGooglePlayServicesAvailable(context);
return resultCode == ConnectionResult.SUCCESS;

google nearby connection access to api

I have a problem with the last update of the google nearby connections API.
When I call start Discovery () or start Advertising () before the update I needed to pass a googleApiClient as a parameter.
After the update, I don't need to do this, but I still need to access the api with googleApiClient.
How can I run the sample without using googleApiClient?
private void startAdvertising() {
Nearby.getConnections(context).startAdvertising(
getUserNickname(),
SERVICE_ID,
mConnectionLifecycleCallback,
new AdvertisingOptions(STRATEGY))
.addOnSuccessListener(
new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void unusedResult) {
// We're advertising!
}
})
.addOnFailureListener(
new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
// We were unable to start advertising.
}
});
}
Use Nearby.Connections instead of Nearby.getConnections.
Use Nearby.getConnectionsClient(Context), to use the API without making a GoogleApiClient.

What Payload to send to the Chromecast Default Media Receiver via Cast.CastApi.sendMessage

I have been trying to build a little test application that sends data from an android app (sender) to my chromecast. I am using the Default Media Receiver to avoid paying for registration while I learn.
All the code is implemented in an service, the receiver is found and ready but i don't know how to format the payload to actually get the Media Receiver to do anything (display images for example)
Here is a bit of code (if more is needed I gladly post it). The onConnected() method is called and runs without errors, the receiver is connected and ready, showing the chromecast symbol but the picture of which I send the URL is not shown.
private class ConnectionCallbacks implements GoogleApiClient.ConnectionCallbacks
{
#Override
public void onConnected(Bundle bundle)
{
Log.d(TAG, "on connected for callback");
Cast.CastApi.launchApplication(mApiClient,
CastMediaControlIntent.DEFAULT_MEDIA_RECEIVER_APPLICATION_ID, false)
.setResultCallback(new ResultCallback<Cast.ApplicationConnectionResult>()
{
#Override
public void onResult(Cast.ApplicationConnectionResult result)
{
Log.d(TAG, "OnResultCallback... ");
Status status = result.getStatus();
Log.d(TAG, "ApplicationConnectionResultCallback.onResult: statusCode" + status.getStatusCode());
if (status.isSuccess())
{
mApplicationStarted=true;
ApplicationMetadata applicationMetadata = result.getApplicationMetadata();
mSessionId = result.getSessionId();
String applicationStatus = result.getApplicationStatus();
boolean wasLaunched = result.getWasLaunched();
Log.d(TAG, mSessionId+" "+applicationStatus);
try
{
Cast.CastApi.sendMessage(mApiClient, "urn:x-cast:com.google.cast.media",
"http://www.randomwebsite.com/images/head.jpg")
.setResultCallback(new ResultCallback<Status>()
{
#Override
public void onResult(Status result)
{
if (!result.isSuccess())
{
Log.e(TAG, "Sending message failed");
}
}
});
}
catch(Exception e)
{
Log.e(TAG, "Sending message to chromecast failed... hard.");
}
}
}
});
}
#Override
public void onConnectionSuspended(int i)
{
Log.d(TAG, "on connection suspended for callback");
}
}
This and most of the code is similar to the https://github.com/googlecast/CastHelloText-android example from google.
My problem, I think is the line Cast.CastApi.sendMessage(mApiClient, "urn:x-cast:com.google.cast.media", "http://www.randomwebsite.com/images/head.jpg") especially the third parameter which i suspect just isn't formatted the way the Default Media Receiver expects data. However I could not find any working examples on this.
So, how does one get a working example using the Default Media Receiver to run?
If you want to send you own messages (non-media), you should create a custom receiver with your own namespace. The Default Receiver/Styled Receiver only understands media namespace and to use that namespace, do not use sendMessage; use RemoteMediaPlayer to send common actions like play/pause/stop/seek/... There are some samples on our GitHub repo.

WiFiDirect discoverServices keeps failing with error 3 (NO_SERVICE_REQUESTS)

I'm using WiFi P2P for network service discovery, and I'm following the instructions as outlined on the developer guide. Here's the relevant code in my service class:
public void onCreate() {
manager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);
channel = manager.initialize(this, getMainLooper(), null);
registerP2pService();
lookForServices();
}
private void registerP2pService() {
WifiP2pDnsSdServiceInfo serviceInfo =
WifiP2pDnsSdServiceInfo.newInstance("_service.name", "_presence._tcp", new HashMap<String, String>());
manager.addLocalService(channel, serviceInfo, new WifiP2pManager.ActionListener() {
#Override
public void onSuccess() {
Log.i("tag", "REGISTERED SERVICE");
}
#Override
public void onFailure(int arg0) {
Log.e("tag", "FAILED to register service");
}
});
}
private void setServiceListeners() {
WifiP2pDnsSdServiceRequest serviceRequest = WifiP2pDnsSdServiceRequest.newInstance();
manager.addServiceRequest(channel, serviceRequest,
new WifiP2pManager.ActionListener() {
#Override
public void onSuccess() {
Log.d("SCOPE", "Added a service request.");
discoverServices();
}
#Override
public void onFailure(int code) {
Log.e("tag", "Error adding service request.");
}
});
}
public void discoverServices() {
manager.discoverServices(channel, new WifiP2pManager.ActionListener() {
#Override
public void onSuccess() {
Log.d("tag", "Service discovery was initiated");
}
#Override
public void onFailure(int code) {
// This is where it keeps failing with error code 3 (NO_SERVICE_REQUESTS)
Log.d("SCOPE", "Service discovery failure code " + code);
}
});
}
The first time I run my service after rebooting the phone, service discovery is initiated just fine, but if I kill the service by stopping it from the app settings page, then open it again, it always fails with error code 3. If I reboot my phone and run the app again it works just fine. I am confused because I am explicitly calling discoverServices only when the service request has been successfully added.
My hunch is that it may be due to some code that is unrelated to service discovery because the service discovery code seems extremely straightforward, but if you see anything wrong with what I've posted, let me know. I'm grasping at straws here.
I'm running this on a Nexus 5 with Android 4.4.2.
I'm seeing this same problem on a second generation Nexus 7. It works fine the first time, subsequent attempts error out. Specifically, the addServiceRequest action listener reports success, but then discoverServices reports NO_SERVICE_REQUESTS.
(Teardown removeLocalService and removeServiceRequest succeed before exiting the app after the initial successful use.)
While it isn't an ideal answer, toggling wifi off then on again appears to reset whatever is stuck. That can be done programatically.
WifiDirect/NSD on Android has been a thorn in my side for the last couple of weeks.
I spent half of last week trying to figure out why my peer discovery calls would fail without any consistency with NO_SERVICE_REQUESTS and finally found a solution that works fairly well. It does seem to be a bug in the OS, and luckily the fine folks of P2Feed figured out a workaround:
if (code == WifiP2pManager.NO_SERVICE_REQUESTS) {
// initiate a stop on service discovery
manager.stopPeerDiscovery(channel, new WifiP2pManager.ActionListener() {
#Override
public void onSuccess() {
// initiate clearing of the all service requests
manager.clearServiceRequests(channel, new WifiP2pManager.ActionListener() {
#Override
public void onSuccess() {
// reset the service listeners, service requests, and discovery
setServiceListeners();
}
#Override
public void onFailure(int i) {
Log.d(TAG, "FAILED to clear service requests ");
}
});
}
#Override
public void onFailure(int i) {
Log.d(TAG, "FAILED to stop discovery");
}
});
}

android mqtt-client-1.5 listener with apollo

https://github.com/fusesource/mqtt-client
i have an android application starting a background service where i have initiated an mqtt connection towards an apollo broker. when startService is called im initiating the MQTT from the onStartCommand setting hostname, port username, password etc.. followed by
connection = mqtt.callbackConnection();
the connect is successfull and i can clearly see that i have a consumer on my topic "uniqueId".
But when i send messages to my topic , the listener never calles the onPublish.. Another strange occurence is that if i loose my connection towards the broker , e.g i shut down the broker so that the active connection is broken, when the mqtt-client reconnects, it seems that it calles the listener and also the onPublish because then all the messages that i have stacked on my durable subscriber topic is delivered.. am i missing anything here regarding the listener?
isnt it suppose to actively consume the topic due to connection.subscribe??
Topic[] topics = { new Topic("uniqueId", QoS.AT_LEAST_ONCE) };
connection.subscribe(topics, new Callback<byte[]>() {
public void onSuccess(byte[] qoses) {
}
public void onFailure(Throwable value) {
value.printStackTrace();
}
});
connection.listener(new Listener() {
#Override
public void onConnected() {
}
#Override
public void onDisconnected() {
}
#Override
public void onFailure(Throwable value) {
}
#Override
public void onPublish(UTF8Buffer topic, Buffer payload, Runnable ack) {
ack.run();
}
});
I'm not familiar with Apollo, but I agree that the behaviour sounds incorrect. You could try testing against another broker to see if it works as expected, then file a bug against Apollo if necessary.
You could use e.g. test.mosquitto.org:1883 to test against, or use one of the other public ones listed on mqtt.org/software

Categories

Resources