My serser uses Java with SpringBoot and my client is an expo react native app which uses typescript.
I am really blocked by this feature: I want to sens push notifications. I tried a lot of methods, but I didn't succeed.
On the client side I am using the method described in expo documentation: https://docs.expo.dev/push-notifications/overview/.
When I use their tool to send test notifications(https://expo.dev/notifications), I receive them on my device.
I didn't manage to send notifications from my client app. I tried all I found on the Inthernet. When I used FirebaseMessagingService and I used the server key from the firebase project as token, I received the SENDER_ID_MISMATCH error.
#Service
public class FirebaseMessagingService {
private final FirebaseMessaging firebaseMessaging;
public FirebaseMessagingService(FirebaseMessaging firebaseMessaging) {
this.firebaseMessaging = firebaseMessaging;
}
public String sendNotification(Note note, String topic) throws FirebaseMessagingException {
Notification notification = Notification
.builder()
.setTitle(note.getSubject())
.setBody(note.getContent())
.setImage(note.getImage())
.build();
Message message = Message
.builder()
.setNotification(notification)
.putAllData(note.getData())
.setToken(topic)
.build();
return firebaseMessaging.send(message);
}
}
I also found the expo-server-sdk-java but I couldn't manage to integrate it.
Any heeeeelp, pleaseeee?
not sure if it's the best practice but it works fine for me.
My pom
<dependency>
<groupId>io.github.jav</groupId>
<artifactId>expo-server-sdk</artifactId>
<version>1.1.0</version>
</dependency>
Then in the java class
private static void sendPushNotification(String token, String titulo, String mensaje, Map<String, Object> data) throws PushClientException {
if (!PushClient.isExponentPushToken(token)) throw new Error("Token:" + token + " is not a valid token.");
ExpoPushMessage expoPushMessage = new ExpoPushMessage();
expoPushMessage.getTo().add(token);
expoPushMessage.setTitle(titulo);
expoPushMessage.setBody(mensaje);
expoPushMessage.setData(data);
List<ExpoPushMessage> expoPushMessages = new ArrayList<>();
expoPushMessages.add(expoPushMessage);
PushClient client = new PushClient();
List<List<ExpoPushMessage>> chunks = client.chunkPushNotifications(expoPushMessages);
List<CompletableFuture<List<ExpoPushTicket>>> messageRepliesFutures = new ArrayList<>();
for (List<ExpoPushMessage> chunk : chunks) {
messageRepliesFutures.add(client.sendPushNotificationsAsync(chunk));
}
// Wait for each completable future to finish
List<ExpoPushTicket> allTickets = new ArrayList<>();
for (CompletableFuture<List<ExpoPushTicket>> messageReplyFuture : messageRepliesFutures) {
try {
allTickets.addAll(messageReplyFuture.get());
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
List<ExpoPushMessageTicketPair<ExpoPushMessage>> zippedMessagesTickets = client.zipMessagesTickets(expoPushMessages, allTickets);
List<ExpoPushMessageTicketPair<ExpoPushMessage>> okTicketMessages = client.filterAllSuccessfulMessages(zippedMessagesTickets);
String okTicketMessagesString = okTicketMessages.stream().map(p -> "Title: " + p.message.getTitle() + ", Id:" + p.ticket.getId()).collect(Collectors.joining(","));
LOGGER.info("Recieved OK ticket for " + okTicketMessages.size() + " messages: " + okTicketMessagesString);
List<ExpoPushMessageTicketPair<ExpoPushMessage>> errorTicketMessages = client.filterAllMessagesWithError(zippedMessagesTickets);
String errorTicketMessagesString = errorTicketMessages.stream().map(p -> "Title: " + p.message.getTitle() + ", Error: " + p.ticket.getDetails().getError()).collect(Collectors.joining(","));
LOGGER.error("Recieved ERROR ticket for " + errorTicketMessages.size() + " messages: " + errorTicketMessagesString);
/**
// Countdown 30s
int wait = 30;
for (int i = wait; i >= 0; i--) {
System.out.print("Waiting for " + wait + " seconds. " + i + "s\r");
Thread.sleep(1000);
}
System.out.println("Fetching reciepts...");
List<String> ticketIds = (client.getTicketIdsFromPairs(okTicketMessages));
CompletableFuture<List<ExpoPushReceipt>> receiptFutures = client.getPushNotificationReceiptsAsync(ticketIds);
List<ExpoPushReceipt> receipts = new ArrayList<>();
try {
receipts = receiptFutures.get();
} catch (ExecutionException | InterruptedException e) {
e.printStackTrace();
}
System.out.println("Recieved " + receipts.size() + " receipts:");
for (ExpoPushReceipt reciept : receipts) {
System.out.println("Receipt for id: " + reciept.getId() + " had status: " + reciept.getStatus());
}
*/
}
In the App.js from react native project with EXPO 44 i take expo token in this way
async function registerForPushNotificationsAsync() {
let token;
if (isDevice) {
const { status: existingStatus } =
await Notifications.getPermissionsAsync();
let finalStatus = existingStatus;
if (existingStatus !== "granted") {
const { status } = await Notifications.requestPermissionsAsync();
finalStatus = status;
}
if (finalStatus !== "granted") {
alert("Failed to get push token for push notification!");
return;
}
token = (await Notifications.getExpoPushTokenAsync()).data;
}
if (Platform.OS === "android") {
Notifications.setNotificationChannelAsync("default", {
name: "default",
importance: Notifications.AndroidImportance.MAX,
vibrationPattern: [0, 250, 250, 250],
lightColor: "#FF231F7C",
});
}
return token;
}
effect from App.js
useEffect(() => {
initFirebaseApp();
registerForPushNotificationsAsync().then(async (token) => {
//store in some place token
});
// This listener is fired whenever a notification is received while the app is foregrounded
notificationListener.current =
Notifications.addNotificationReceivedListener(handleNotification);
// This listener is fired whenever a user taps on or interacts with a notification (works when app is foregrounded, backgrounded, or killed)
responseListener.current =
Notifications.addNotificationResponseReceivedListener(
handleNotificationResponse
);
return () => {
Notifications.removeNotificationSubscription(
notificationListener.current
);
Notifications.removeNotificationSubscription(responseListener.current);
};
}, []);
notification handlers in App.js
const handleNotification = (response) => {
// console.log(response);
};
const handleNotificationResponse = (response) => {
// console.log(response)
};
I hope this helps you
Docs
Expo SDK documentation
Expo docs reference
Related
I try to use Google Consent with the User Messaging Platform to show in Android app consent form. I follow this documentation https://developers.google.com/admob/ump/android/quick-start.
I get this error:
onConsentInfoUpdateFailure: Publisher misconfiguration: Failed to read publisher's account configuration; please check your configured app ID. Received app ID: `ca-app-pub-XXXXXXXXXXXXXXXX~XXXXXXXXXX`.
My Code:
ConsentRequestParameters params;
if (testingGDPR) {
ConsentDebugSettings debugSettings = new ConsentDebugSettings.Builder(this)
.setDebugGeography(ConsentDebugSettings.DebugGeography.DEBUG_GEOGRAPHY_EEA)
.addTestDeviceHashedId(getString(R.string.ADMOB_REAL_DEVICE_HASH_ID_FOR_TESTING))
.build();
params = new ConsentRequestParameters.Builder().setConsentDebugSettings(debugSettings).build();
} else {
params = new ConsentRequestParameters.Builder().build();
}
consentInformation = UserMessagingPlatform.getConsentInformation(this);
if (testingGDPR) {
consentInformation.reset();
}
consentInformation.requestConsentInfoUpdate(
this,
params,
new ConsentInformation.OnConsentInfoUpdateSuccessListener() {
#Override
public void onConsentInfoUpdateSuccess() {
if (consentInformation.isConsentFormAvailable() && consentInformation.getConsentStatus() == ConsentInformation.ConsentStatus.REQUIRED) {
loadForm();
} else {
setupAds();
}
}
},
new ConsentInformation.OnConsentInfoUpdateFailureListener() {
#Override
public void onConsentInfoUpdateFailure(FormError formError) {
Log.d("gdpr", "onConsentInfoUpdateFailure, code:" + formError.getErrorCode() + ", " + formError.getMessage());
}
});
The TestDeviceHashedId is not the same thing as the Admob Device Id.
So remove this line:
.addTestDeviceHashedId(getString(R.string.ADMOB_REAL_DEVICE_HASH_ID_FOR_TESTING))
Then run your code and check for the log. The TestDeviceHashedId you should use will appear.
I am working on receiving pending messages in Azure Service Bus queue.
I have created a queue (SampleQueue) in Azure ServiceBus and I am able to send the message successfully in that queue via POSTMAN using a SAS token which I generate with my Java program.
I am also getting a 201 created status after hitting my service bus queue api url(below image).
I want to receive the message pending in my Service bus queue. I went through some links about receiving message (https://learn.microsoft.com/en-us/azure/service-bus-messaging/service-bus-java-how-to-use-queues), but this does not contain information about how I can receive and view those messages.
My Java code that receives the message from Service bus queue looks like below[I am a novice in Java]:-
public class Test2 {
public static void main(String[] args) throws ServiceException {
String namespace = "SampleNamespace";
String sharedKeyName = "RootManageSharedAccessKey";
String sharedSecretKey = "t+U5ERMAnIyxgEUDUouGOKn6ADM/CuLWzEJZtauwVsc=";
String queueName = "QueueName";
// Azure Service Bus Service
com.microsoft.windowsazure.Configuration config = ServiceBusConfiguration.configureWithSASAuthentication(namespace, sharedKeyName, sharedSecretKey, ".servicebus.windows.net");
ServiceBusContract service = ServiceBusService.create(config);
// Receive and Delete Messages
ReceiveMessageOptions opts = ReceiveMessageOptions.DEFAULT;
opts.setReceiveMode(ReceiveMode.RECEIVE_AND_DELETE);
while (true) {
ReceiveQueueMessageResult resultQM = service.receiveQueueMessage(queueName , opts);
BrokeredMessage message = resultQM.getValue();
if (message != null && message.getMessageId() != null) {
System.out.println("Body: " + message.toString());
System.out.println("MessageID: " + message.getMessageId());
} else {
System.out.println("No more messages.");
break;
}
}
}
}
But when I run this code, I get the below error:-
Exception in thread "main" java.lang.NoClassDefFoundError: javax/ws/rs/WebApplicationException
at java.lang.Class.getDeclaredConstructors0(Native Method)
at java.lang.Class.privateGetDeclaredConstructors(Class.java:2671)
at java.lang.Class.getConstructors(Class.java:1651)
at com.microsoft.windowsazure.core.DefaultBuilder.findInjectConstructor(DefaultBuilder.java:67)
at com.microsoft.windowsazure.core.DefaultBuilder.add(DefaultBuilder.java:94)
at com.microsoft.windowsazure.services.servicebus.Exports.register(Exports.java:34)
at com.microsoft.windowsazure.core.DefaultBuilder.create(DefaultBuilder.java:46)
at com.microsoft.windowsazure.Configuration.<init>(Configuration.java:80)
at com.microsoft.windowsazure.Configuration.load(Configuration.java:100)
at com.microsoft.windowsazure.Configuration.getInstance(Configuration.java:90)
at com.microsoft.windowsazure.services.servicebus.ServiceBusConfiguration.configureWithSASAuthentication(ServiceBusConfiguration.java:252)
at com.rocky.servicebus.queue.Test2.main(Test2.java:24)
Caused by: java.lang.ClassNotFoundException: javax.ws.rs.WebApplicationException
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
Can anyone please help in rectifying what I am doing wrong?
Would be greatful for any help.
Thanks,
Rudra
Based on the tutorial for receiving message, you need to create a queue client, and register a message handler for it.
A) Get connection string.
B) A code sample for sending and receiving messages
public static void registerReceiver(QueueClient queueClient, ExecutorService executorService) throws Exception {
queueClient.registerMessageHandler(
new IMessageHandler() {
public CompletableFuture<Void> onMessageAsync(IMessage message) {
if (message.getLabel() != null &&
message.getContentType() != null &&
message.getLabel().contentEquals("TestMessage") &&
message.getContentType().contentEquals("text/plain")) {
System.out.printf(
"\nMessage received: \n -->MessageId = %s\n -->ContentType = %s\n -->Content = %s\n",
message.getMessageId(),
message.getContentType(),
new String(message.getBody())
);
return queueClient.completeAsync(message.getLockToken());
}
return queueClient.abandonAsync(message.getLockToken());
}
public void notifyException(Throwable throwable, ExceptionPhase exceptionPhase) {
System.out.printf(exceptionPhase + "-" + throwable.getMessage());
}
},
new MessageHandlerOptions(1, false, Duration.ofSeconds(10)),
executorService
);
}
public static void sendMessages(QueueClient client) throws ServiceBusException, InterruptedException {
for (int i = 0; i < 100; i++) {
String messageId = Integer.toString(i);
Message message = new Message("This is message " + i);
message.setContentType("text/plain");
message.setLabel("TestMessage");
message.setMessageId(messageId);
message.setTimeToLive(Duration.ofMinutes(10));
client.send(message);
System.out.printf("Message sent: Id = %s \n", message.getMessageId());
}
}
public static void main(String[] args) throws Exception {
String connectionString = "your_connection_string, Endpoint=sb://j*9.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=V*=";
String queueName = "your_queue_name, testQueue";
QueueClient client = new QueueClient(new ConnectionStringBuilder(connectionString, queueName), ReceiveMode.PEEKLOCK);
sendMessages(client);
client.close();
QueueClient receiveClient = new QueueClient(new ConnectionStringBuilder(connectionString, queueName), ReceiveMode.PEEKLOCK);
ExecutorService executorService = Executors.newSingleThreadExecutor();
registerReceiver(receiveClient, executorService);
Thread.sleep(60 * 1000); // Wait for 60 seconds to receive all the messages.
receiveClient.close();
executorService.shutdown();
}
Result:
100 messages will be sent.
Message sent: Id = 0
Message sent: Id = 1
Message sent: Id = 2
Message sent: Id = 3
*
*
*
Message sent: Id = 99
And then will start to receive messages.
Message received:
-->MessageId = 0
-->ContentType = text/plain
-->Content = This is message 0
Message received:
-->MessageId = 1
-->ContentType = text/plain
-->Content = This is message 1
Message received:
-->MessageId = 2
-->ContentType = text/plain
-->Content = This is message 2
*
*
*
Message received:
-->MessageId = 99
-->ContentType = text/plain
-->Content = This is message 99
For all the wanderers, below is the working Java code to fetch pending messages from Azure SB Queue:-
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;
import com.microsoft.windowsazure.services.servicebus.ServiceBusConfiguration;
import com.microsoft.windowsazure.services.servicebus.ServiceBusContract;
import com.microsoft.windowsazure.services.servicebus.ServiceBusService;
import com.microsoft.windowsazure.services.servicebus.models.BrokeredMessage;
import com.microsoft.windowsazure.services.servicebus.models.ReceiveMessageOptions;
import com.microsoft.windowsazure.services.servicebus.models.ReceiveMode;
import com.microsoft.windowsazure.services.servicebus.models.ReceiveQueueMessageResult;
public class Test1 {
//static StringWriter writer = new StringWriter();
public static void main(String...s) throws Exception{
com.microsoft.windowsazure.Configuration config = ServiceBusConfiguration.configureWithSASAuthentication("Your_NameSpace", "RootManageSharedAccessKey", "Mkf1H3g9qg0LrNEP1QbZ/EJKSARmJZQdOI6ek6obalI=", ".servicebus.windows.net");
ServiceBusContract service = ServiceBusService.create(config);
ReceiveMessageOptions opts = ReceiveMessageOptions.DEFAULT;
opts.setReceiveMode(ReceiveMode.PEEK_LOCK);
while(true)
{
ReceiveQueueMessageResult resultQM = service.receiveQueueMessage("Queue_Name", opts);
BrokeredMessage message = resultQM.getValue();
if (message != null && message.getMessageId() != null)
{
try
{
// IOUtils.copy(message.getBody(), writer, encoding);
Scanner s1 = new Scanner(message.getBody()).useDelimiter("\\A");
String result = s1.hasNext() ? s1.next() : "";
//above will convert InputStream in String
System.out.println("Body: " + message.toString());
System.out.println("MainBody : " + result );
System.out.println("MessageID: " + message.getMessageId());
System.out.println("Custom Property: " +
message.getProperty("TestProperty"));
// Remove message from queue
System.out.println("Deleting this message.");
service.deleteMessage(message);
}
catch (Exception ex)
{
// Indicate a problem, unlock message in queue
System.out.println("Inner exception encountered!");
service.unlockMessage(message);
}
}
else
{
System.out.println("Finishing up - no more messages.");
break;
// Added to handle no more messages in the queue.
// Could instead wait for more messages to be added.
}
}
}
}
Make sure to get required Maven Dependencies for "BrokeredMessage".
Thanks,
Rudra
I am trying to save a new document to MongoDB using the Vertx MongoClient as follows:
MongoDBConnection.mongoClient.save("booking", query, res -> {
if(res.succeeded()) {
documentID = res.result();
System.out.println("MongoDB inserted successfully. + document ID is : " + documentID);
}
else {
System.out.println("MongoDB insertion failed.");
}
});
if(documentID != null) {
// MongoDB document insertion successful. Reply with a booking ID
String resMsg = "A confirmed booking has been successfully created with booking id as " + documentID +
". An email has also been triggered to the shared email id " + emailID;
documentID = null;
return new JsonObject().put("fulfillmentText", resMsg);
}
else {
// return intent response
documentID = null;
return new JsonObject().put("fulfillmentText",
"There is some issues while booking the shipment. Please start afreash.");
}
The above code successfully writes the query jsonObject to MongoDB collection booking. However, the function which contains this code always returns with There is some issues while booking the shipment. Please start afreash.
This is happening probably because the MongoClient save() handler "res" is asynchronous. But, I want to return conditional responses based on successful save() operation and on failed save operation.
How to achieve it in Vertx Java?
Your assumption is correct, you dont wait for the async response from the database. What you can do, is to wrap it in a Future like this:
public Future<JsonObject> save() {
Future<JsonObject> future = Future.future();
MongoDBConnection.mongoClient.save("booking", query, res -> {
if(res.succeeded()) {
documentID = res.result();
if(documentID != null) {
System.out.println("MongoDB inserted successfully. + document ID is : " + documentID);
String resMsg = "A confirmed booking has been successfully created with booking id as " + documentID +
". An email has also been triggered to the shared email id " + emailID;
future.complete(new JsonObject().put("fulfillmentText", resMsg));
}else{
future.complete(new JsonObject().put("fulfillmentText",
"There is some issues while booking the shipment. Please start afreash."))
}
} else {
System.out.println("MongoDB insertion failed.");
future.fail(res.cause());
}
});
return future;
}
Then i assume you have and endpoint that eventually calls this, eg:
router.route("/book").handler(this::addBooking);
... then you can call the save method and serve a different response based on the result
public void addBooking(RoutingContext ctx){
save().setHandler(h -> {
if(h.succeeded()){
ctx.response().end(h.result());
}else{
ctx.response().setStatusCode(500).end(h.cause());
}
})
}
You can use RxJava 2 and a reactive Mongo Client (io.vertx.reactivex.ext.mongo.MongoClient)
Here is a code snippet:
Deployer
public class Deployer extends AbstractVerticle {
private static final Logger logger = getLogger(Deployer.class);
#Override
public void start(Future<Void> startFuture) {
DeploymentOptions options = new DeploymentOptions().setConfig(config());
JsonObject mongoConfig = new JsonObject()
.put("connection_string",
String.format("mongodb://%s:%s#%s:%d/%s",
config().getString("mongodb.username"),
config().getString("mongodb.password"),
config().getString("mongodb.host"),
config().getInteger("mongodb.port"),
config().getString("mongodb.database.name")));
MongoClient client = MongoClient.createShared(vertx, mongoConfig);
RxHelper.deployVerticle(vertx, new BookingsStorage(client), options)
.subscribe(e -> {
logger.info("Successfully Deployed");
startFuture.complete();
}, error -> {
logger.error("Failed to Deployed", error);
startFuture.fail(error);
});
}
}
BookingsStorage
public class BookingsStorage extends AbstractVerticle {
private MongoClient mongoClient;
public BookingsStorage(MongoClient mongoClient) {
this.mongoClient = mongoClient;
}
#Override
public void start() {
var eventBus = vertx.eventBus();
eventBus.consumer("GET_ALL_BOOKINGS_ADDRESS", this::getAllBookings);
}
private void getAllBookings(Message msg) {
mongoClient.rxFindWithOptions("GET_ALL_BOOKINGS_COLLECTION", new JsonObject(), sortByDate())
.subscribe(bookings -> {
// do something with bookings
msg.reply(bookings);
},
error -> {
fail(msg, error);
}
);
}
private void fail(Message msg, Throwable error) {
msg.fail(500, "An unexpected error occurred: " + error.getMessage());
}
private FindOptions sortByDate() {
return new FindOptions().setSort(new JsonObject().put("date", 1));
}
}
HttpRouterVerticle
// inside a router handler:
vertx.eventBus().rxSend("GET_ALL_BOOKINGS_ADDRESS", new JsonObject())
.subscribe(bookings -> {
// do something with bookings
},
e -> {
// handle error
});
I want to send a message from Amazon Simple Notification Service (SNS) using Play framework, and I read that I have to use WS for REST APIs. However, I am confused on how to do this. Can anyone help me work this out?
First of all, you need to add SNS SDK to your project by adding the following line into your build.sbt:
libraryDependencies += "com.amazonaws" % "aws-java-sdk-sns" % "1.11.271"
then use your service by injecting it with your controller, your service should be something like:
#Singleton
public final class AmazonSNSService {
// logging always a good thing to do
private final Logger.ALogger logger = Logger.of(this.getClass());
// this is what you have to use
private final com.amazonaws.services.sns.AmazonSNS snsClient;
private final String AMAZON_ARN;
#Inject
public AmazonSNSService(Configuration configuration) { // or Config if play 2.6 and later
// I set the aws config in application.conf and I read them here
final String AWS_ACCESS_KEY = configuration.getString("aws_access_key");
final String AWS_SECRET_KEY = configuration.getString("aws_secrect_key");
snsClient = AmazonSNSClient.builder()
.withRegion(Regions.US_EAST_1)
.withCredentials(new AWSStaticCredentialsProvider(new BasicAWSCredentials(AWS_ACCESS_KEY, AWS_SECRET_KEY)))
.build();
AMAZON_ARN = configuration.getString("amazon_arn_config_key");
}
}
then you can use snsClient with methods you do want, for creating a topic:
public void createTopic(String topicName) {
String topicARN = AMAZON_ARN + ":" + topicName;
if (doesTopicExists(topicARN)) {
logger.debug("TopicArn - already Exists" + topicARN);
} else {
//create a new SNS topic
CreateTopicRequest createTopicRequest = new CreateTopicRequest(topicName);
CreateTopicResult createTopicResult = snsClient.createTopic(createTopicRequest);
//get request id for CreateTopicRequest from SNS metadata
ResponseMetadata topicResponse = snsClient.getCachedResponseMetadata(createTopicRequest);
logger.debug("CreateTopicArn - " + createTopicResult.getTopicArn());
}
}
And another example to subscribe to the topic:
public String subscribeToTopic(String topicName, String deviceEndpointARN) {
String topicARN = AMAZON_ARN + ":" + topicName;
//if topic does not exists create topic then subscribe
if (!doesTopicExists(topicARN)) {
createTopic(topicName);
}
return subscribeToTopic(topicARN, deviceEndpointARN);
}
Want push to the topic?:
public void publishToTopic(String message, String topicName) {
String topicARN = AMAZON_ARN + ":" + topicName;
//if topic does not exists create topic then publish to topic
// or throw an exception, maybe it does not make sense to push to the topic that have no subscribers at all.
if (!doesTopicExists(topicARN)) {
createTopic(topicName);
}
//publish to an SNS topic
PublishRequest publishRequest = new PublishRequest(topicARN, message);
publishRequest.setMessageStructure("json");
PublishResult publishResult = snsClient.publish(publishRequest);
//print MessageId of message published to SNS topic
logger.debug("Push Notification sent to TOPIC [" + topicARN + "] MessageId - [" + publishResult.getMessageId() + "] Message Body: " + message);
}
And this is how I check if the topic exists or not:
private boolean doesTopicExists(String topicARN) {
String nextToken = null;
do {
ListTopicsRequest request = new ListTopicsRequest();
request.setNextToken(nextToken);
ListTopicsResult listTopicsResult = snsClient.listTopics();
List<Topic> topics = listTopicsResult.getTopics();
for (Topic topic : topics) {
if (topic.getTopicArn().equals(topicARN)) {
return true;
}
}
nextToken = request.getNextToken();
} while (nextToken != null);
return false;
}
For more, check java doc of them and search for examples,
Have fun!
Cordova Web View sendjavascript is deprecated and it not working for me.
My java code is:
public static void sendJavascript(JSONObject _json) {
String _d = "javascript:" + gECB + "(" + _json.toString() + ")";
Log.v(TAG, "sendJavascript: " + _d);
Log.i(TAG,_d);
if (gECB != null && gWebView != null) {
gWebView.sendJavascript(_d);//deprecated method
}
}
My java script code :
document.addEventListener("deviceready", function(){
window.plugins.pushNotification.register(successHandler, errorHandler, {
ecb : 'onNotificationGCM',
senderID : 'xxxxxxxxxxxxx'
});
// Method to handle device registration for Android.
var onNotificationGCM = function(e) {
if('registered' === e.event) {
// Successfully registered device.
alert(e.regid);
}
else if('error' === e.event) {
// Failed to register device.
alert(e.msg);
}
else if('message' === e.event) {
//mesage recived
alert(e.payload.message);
}
};
// result contains any message sent from the plugin call
function successHandler (result) {
alert('gcm result = ' + result);
}
// result contains any error description text returned from the plugin call
function errorHandler (error) {
alert('error = ' + error);
}
});
Deprecated details :https://apache.googlesource.com/cordova-android/+/3.6.1/framework/src/org/apache/cordova/CordovaWebView.java
Please help me?
This should work for you:
gWebView.loadUrl("javascript:myJavaScriptFuntion();");