I am creating a project on Google Cloud Messaging (GCM) and am following this tutorial.
I am done with the client-side work and set up the device on the client side. Also I had registered the device using the following code.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
GCMRegistrar.checkDevice(this);
GCMRegistrar.checkManifest(this);
final String regId = GCMRegistrar.getRegistrationId(this);
if (regId.equals("")) {
GCMRegistrar.register(this, "483910217912");
Log.d(tag, "Registered");
}
else {
Log.v(tag, "Already registered");
}
}
Now I am stuck at a point to create server for my GCM project. Note that I am creating a project to notify when a new message is received. However, I had not implemented the service to receive a message, but I will implement it when the server setting is finished.
You can create a GCM server in Android using the blog post Google cloud Messaging (GCM) tutorial , but I would prefer to use PHP for server side code. You can create a GCM Server in cURL (PHP) in easy steps:
Create a server key from the Google API console page.
Identify the device token of a device for which this message is sent to.
You can find the easy steps in How to implement a GCM PHP push server for Android to implement the push server.
you can use this code
package yourpackage.android.gcm.server;
import com.google.android.gcm.server.Message;
import com.google.android.gcm.server.MulticastResult;
import com.google.android.gcm.server.Sender;
import java.util.ArrayList;
class Notify {
public static void main(String args[]) {
try {
Sender sender = new Sender("AIzaSyCn3N2OIm-EDtiGwTyQfSIB8NRvDtIOx30");
ArrayList<String> devicesList = new ArrayList<String>();
//add you deviceID
devicesList.add("APA91bELVJbxB_NLnLbTkkkX87SDdkJc6OfCN2slhC9t4cLq-KA32eGgiW4-Gi--ZEsEMKIh0AtYJMs5rQGswfm3cH1qK853WcpV98bkaplAaC5AiycDmifuVFSRl21vgf-Rqj0dCrFF");
//devicesList.add("APA91bHIdM4XGqrjJLTuwCX5OOrTYG4ACXYEVkZDM1bPs5qFdzJP4Bpql-sZqyKB8BU7fDtdxB84aTygHLyASYg_XNY6lqrcA4wj4sZHJXGVFzz_0UEADMfFCx9NAfRZxunIYso_dkBa");
//APA91bFA-i2l3iEMnIBs0JK80pTLHOsE7p1s-DysRpKGas1MQOVILyIs9xwY7soysSWGz5Uif68uXR6F5Xn0tCTYesv78uQZxhC310a1cvf8aFohhfMGY6awbOSg3t1GRz2i3U-8kVSF
// Use this line to send message without payload data
// Message message = new Message.Builder().build();
// use this line to send message with payload data
Message message = new Message.Builder()
//.collapseKey("message")
//.timeToLive(241000)
.delayWhileIdle(true)
.addData("message", "Your message send")
.build();
/**/
// Use this code to send to a single device
// Result result = sender
// .send(message,
// "APA91bGiRaramjyohc2lKjAgFGpzBwtEmI8tJC30O89C2b3IjP1CuMeU1h9LMjKhmWuZwcXZjy1eqC4cE0tWBNt61Kx_SuMF6awzIt8WNq_4AfwflaVPHQ0wYHG_UX3snjp_U-5kJkmysdRlN6T8xChB1n3DtIq98w",
// 1);
// Use this for multicast messages
MulticastResult result = sender.send(message, devicesList, 1);
//sender.send(message, devicesList, 0);
System.out.println(result.toString());
if (result.getResults() != null) {
int canonicalRegId = result.getCanonicalIds();
if (canonicalRegId != 0) {
}
} else {
int error = result.getFailure();
System.out.println(error);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
The com.google.android.gcm.server library is deprecated. Just encode your message to JSON object and POST it to GCM URL https://android.googleapis.com/gcm/send
JSON example:
{
"registration_ids" : ["APA91bHun4MxP5egoKMwt2KZFBaFUH-1RYqx...",...],
"data" : {
"Team" : "Portugal",
"Score" : "3",
"Player" : "Varela",
},
}
Here is more http://developer.android.com/google/gcm/http.html
You can find sample code for gcm-client and gcm-server in the Android SDK directory. It is good point to get started. Directory is :
path_to_android_sdk/extras/google/gcm/samples
In your main function implement following code to send push notification to your app
final String apiKey = "specify your api key generated by gcm";
To make http connection to gcm using following code
URL url = new URL("https://android.googleapis.com/g...");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Authorization", "key="+apiKey);
conn.setDoOutput(true);
JSON message format accepted by GCM
String input = "{\"registration_ids\" : [\"Specify token you got from GCM\"],\"data\" : {\"message\": \"hai welcome\"},}";
To send notification
OutputStream os = conn.getOutputStream();
os.write(input.getBytes());
os.flush();
In your client app you need to have proper BroadcastReceiver class to receive the message sent from GCM
I would insist you to test the demo that is being provided on the develpers site. I had just created a demo sample based on that with all the steps that one should follow for executing the demo sample. You can check my blog and also find the source from my github.
Related
I'm trying to test out Firebase Cloud messaging APIs as all functionality is not available from console (notably customization of notifications when app is in background). But for some reasons, I cannot get it to work, and it always shows up 401 error. I investigated the reasons for this, and tried it after regenerating new server key, but the error remains constant. Surprisingly, when I generated a new server key, it is not reflected in Firebase console and it shows server key as empty. Also, I tried adding my IP address to the server whitelist IPs but still no luck. I've attached a screenshot of a request that I did with Postman (I substitue the server key in place of serverKey.
I'm stuck on this for a few hours and would really appreciate some help.
I don't know if someone uses the [Web API Key] as the [YOUR_SERVER_KEY] for POSTMAN test and keep getting '401 Error'. [Web API Key] is not [YOUR_SERVER_KEY].
You should go to your Firebase console and check this:
to get the correct Server key.
Hope it help.
I noticed from your screenshot that you were using "key: serverKey". Could you try using "key=serverKey" instead?
Also you don't need to have "POST fcm.googleapus.com/fcm/send"; this is not proper json and would explain the error you are seeing. The URL of the request is already defined elsewhere so remove it from the payload.
I faced the same problem.
the problem was that I was using the legacy server key. when I used the new version of the server key the problem solved.
in your firebase console goto settings -> cloud messaging
then use the new server key. it is longer than the old version key.
go to https://console.firebase.google.com/u/0/project/[project-name]/settings/cloudmessaging/
you can use Server Key or Legacy server key
I too am facing the Same problem... I am using curl in php for posting and it works only if I have php files stored on my LocalHost server. When I try to use access the files via a free hosting online, then it say Unautorized 401.
So I would suggest if you can, use the Localhost.
I have the same problem at Server Side Code(C#).
You basically used wrong Server Key (or API Key) for service side code.
Follow below Link over stackoverflow posted by me (Helpful to find Server Key (or API Key) )
FCM (Firebase Cloud Messaging) Push Notification with Asp.Net
401 with FCM through HTTPv1 (Error and Solution for Bearer)
If you are using FCM via HTTP v1, then you will have to make two sucessive POST requests:
1/ In the first call, you make a POST request to 'https://accounts.google.com/o/oauth2/token' (or using API packages) using your firebase service account key at
'https://console.firebase.google.com/u/0/project/{{firebaseProjectName}}/settings/serviceaccounts/adminsdk'
to get the access token.
2/ Then you have to make another POST request to 'https://fcm.googleapis.com/v1/projects/{{firebaseProjectName}}/messages:send'. If you have followed the steps for the migration from legacy HTTP to HTTP v1 (very clear documentation) on firebase website, you have to make some small changes at the content of the post request and also using 'Bearer ${accessToken.data}' for the Authorization.
In my case I was not properly awaiting for the accessToken in the first function (forgot the 'await' keyword in front of the function making the post request and AndroidStudio did not notice either that there was something wrong).
Make sure that you await the result of the first post request as it is a Future.
If you don't, Bearer will be null when you make the second POST request because you did not await for it.
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import javax.validation.Valid;
import javax.validation.constraints.Size;
public class PushNotificationSubmit {
public static void main(String[] args) {
new PushNotificationSubmit().send("sample message title", "sample message body");
}
final String serverKey = "AAAA_*******";
final String fcmUrl = "https://fcm.googleapis.com/fcm/send";
/**
* note from google: The value should be an array of registration tokens to which to send the multicast message. The array must contain at least 1 and at most 1000 registration tokens.
* send to specific users
*
* #param messageTitle
* #param messageBody
* #param tokenList
*/
#Size.List({#Size(min = 1), #Size(max = 999)})
public void send(String messageTitle, String messageBody, List<String> tokenList) {
try {
String payloadJson = createMessageAsJson(messageTitle, messageBody, tokenList);
doSend(payloadJson);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* send to all users that registered in my topic
*
* #param messageTitle
* #param messageBody
*/
public void send(String messageTitle, String messageBody) {
try {
String payloadJson = createMessageAsJson(messageTitle, messageBody, null);
doSend(payloadJson);
} catch (Exception e) {
e.printStackTrace();
}
}
private String createMessageAsJson(String messageTitle, String messageBody, List<String> tokenList) {
JSONObject payloadObj = new JSONObject();
try {
JSONObject notifyObj = new JSONObject();
notifyObj.put("title", messageTitle);
notifyObj.put("body", messageBody);
payloadObj.put("notification", notifyObj);
if (tokenList != null) {
if (tokenList != null && tokenList.size() > 0) {
JSONArray regId = new JSONArray();
for (int i = 0; i < tokenList.size(); i++) {
regId.put(tokenList.get(i));
}
payloadObj.put("registration_ids", regId);
}
} else {
payloadObj.put("to", "/topics/all");
}
return payloadObj.toString();
} catch (Exception e) {
// TODO: add logger
e.printStackTrace();
throw e;
}
}
private void doSend(String payloadJson) throws Exception {
HttpClient httpclient = HttpClientBuilder.create().build();
try {
HttpPost httpPost = new HttpPost(fcmUrl);
httpPost.setHeader("Content-Type", "application/json");
httpPost.setHeader("Authorization", "key=" + serverKey);
httpPost.setEntity(new StringEntity(payloadJson, "UTF-8"));
HttpResponse response = httpclient.execute(httpPost);
HttpEntity entity = response.getEntity();
System.out.println("push notification status: " + response.getStatusLine());
EntityUtils.consume(entity);
} finally {
httpclient.getConnectionManager().shutdown();
}
}
}
In C# HttpClient response
For wrong server key it will happen, Invalid Key, Unauthorize, 401
I was facing the same problem, i solved it by using the following steps
1- In the server from where you are sending push, Use the browser key only, you can get it from Firebase console or google api console as I have highlighted in the below images:-
Google api console
Firebase console, click on the project-->settings
Note : The Firebase console web api key and google console browser key are the same you can use either of them
2- If you follow the first step only you will get the Unauthorized error, to resolve this you need to authorize your browser key in google console by adding your server IP address from where you will send the push. Click on the edit pencil icon on the right side of your browser key in google api console, above first image
After adding your Ip address click save
Make sure that your device token is not empty on which you are sending the push, I hope your push will be sent successfully now.
I followed Google Cloud Messaging (GCM) with local device groups on Android gives HTTP Error code 401 to manage local device groups on Android and successfully got a notification key, but when I send message to the notification key, I never get the message back.
Has anyone ever got this work?
My send code is like:
public void sendMessage(View view) {
AsyncTask<Void, Void, String> task = new AsyncTask<Void, Void, String>() {
#Override
protected String doInBackground(Void... params) {
try {
GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(getApplicationContext());
String to = notificationKey; // the notification key
AtomicInteger msgId = new AtomicInteger();
String id = Integer.toString(msgId.incrementAndGet());
Bundle data = new Bundle();
data.putString("hello", "world");
gcm.send(to, id, data);
Log.e(TAG, "sendMessage done.");
} catch (Exception ex) {
Log.e(TAG, ex.toString());
}
return null;
}
};
task.execute();
}
It seems there's a misunderstanding about the GCM concept. The app server is an integral part of GCM messaging.
The server side of Google Cloud Messaging (GCM) consists of two
components:
GCM connection servers provided by Google. These servers take messages
from an app server and send them to a client app running on a device.
Google provides connection servers for HTTP and XMPP.
An application
server that you must implement in your environment. This application
server sends data to a client app via the chosen GCM connection
server, using the appropriate XMPP or HTTP protocol.
Try the Android GCM Playground to get a better understanding of this.
Here's a snippet:
public void sendMessage() {
String senderId = getString(R.string.gcm_defaultSenderId);
if (!("".equals(senderId))) {
String text = upstreamMessageField.getText().toString();
if (text == "") {
showToast("Please enter a message to send");
return;
}
// Create the bundle for sending the message.
Bundle message = new Bundle();
message.putString(RegistrationConstants.ACTION, RegistrationConstants.UPSTREAM_MESSAGE);
message.putString(RegistrationConstants.EXTRA_KEY_MESSAGE, text);
try {
gcm.send(GcmPlaygroundUtil.getServerUrl(senderId),
String.valueOf(System.currentTimeMillis()), message);
showToast("Message sent successfully");
} catch (IOException e) {
Log.e(TAG, "Message failed", e);
showToast("Upstream FAILED");
}
}
}
The to field of the send method represents the sender ID of your project. You cannot use this method to send messages to Instance ID tokens (other devices), Device to Device messaging is not currently supported by GCM.
You are correct to avoid including the API key in your client app, so currently you will need an app server to send these types of messages.
I am facing the issue to retrieve offline message in android apps using smack api from XMPP Mongoose server. As per the code flow Try to retrive offline message when user become login in xmpp mongoose server before sending available presence to mongoose server.
Tried with two different way to retrieve offline message still not able to find working solution for the same. Both method which i tried those all things are explain below with detail.
Below Api we are using for the xmpp connection and all other extension :
// Smack (XMPP Client Library)
compile 'org.igniterealtime.smack:smack-android:4.1.6'
compile 'org.igniterealtime.smack:smack-tcp:4.1.6'
compile 'org.igniterealtime.smack:smack-im:4.1.6'
compile 'org.igniterealtime.smack:smack-android-extensions:4.1.6'
Tried retrive offline message Using offlineMessageManager
Below is code which I tried to retrieve offline message after login and before send available presence to server
try {
Boolean isFelxibleRetrievalSupport = offlineMessageManager.supportsFlexibleRetrieval();
Iterator i = (Iterator) offlineMessageManager.getMessages();
while (i.hasNext())
{
Message msg = i.next();
System.out.println("Got text [" + msg.getBody() + "] from [" + msg.getFrom() + "]");
} catch (XMPPException e)
{
System.out.println("Error Offline Message.");
e.printStackTrace();
}
catch (SmackException.NotConnectedException e)
{
System.out.println("Error Offline Message. No connection");
e.printStackTrace();
}
catch (SmackException.NoResponseException e)
{
System.out.println("Error Offline Message. No Reponse");
e.printStackTrace();
}
Issue case 1:
Below is exception detail which generate when above code execute
I got Exception when execute below line of code.
Iterator i = (Iterator) offlineMessageManager.getMessages();
Below is exception description which Generate when above line execute
org.jivesoftware.smack.XMPPException$XMPPErrorException: XMPPError: service-unavailable - cancel
Issue Case 2:
If checking is Flexible offline message supported from android code using smack from xmmp mongoose server so i got false value. Below is code which i used for testing.
Boolean isFelxibleRetrievalSupport = offlineMessageManager.supportsFlexibleRetrieval();
Issue Case 3:
When I try to retrieve supported features using below method using smack code like below.
ServiceDiscoveryManager manager = ServiceDiscoveryManager
.getInstanceFor(connection);
List AllFetures = manager.getFeatures();
Below is features list which i retrived:
http://jabber.org/protocol/bytestreams,
jabber:iq:privacy, urn:xmpp:ping,
http://jabber.org/protocol/commands,
jabber:iq:version,
jabber:iq:last,
http://jabber.org/protocol/xdata-validate,
http://jabber.org/protocol/xhtml-im,
vcard-temp,
http://jabber.org/protocol/chatstates,
urn:xmpp:receipts, urn:xmpp:time,
http://jabber.org/protocol/xdata-layout,
http://jabber.org/protocol/muc,
http://jabber.org/protocol/disco#items,
http://jabber.org/protocol/disco#info,
http://jabber.org/protocol/caps,
jabber:x:data
Tried to retreive offline message Using package listener from XMPP MongooseIM
below is code which i tried using package listener from smack api 4.1.6.
private static final StanzaFilter MESSAGE_PACKET_FILTER= new OrFilter(StanzaTypeFilter.MESSAGE);
configuration = XMPPTCPConnectionConfiguration.builder()
.setServiceName(SERVICE_NAME)
.setHost(KDevelopmentXMPPServer)
.setPort(PORT)
.setSendPresence(false)
.build();
// Create Connection object of xmpp connection with configured detail
connection = new XMPPTCPConnection(configuration);
connection.addAsyncStanzaListener(new StanzaListener() {
#Override
public void processPacket(Stanza packet) throws SmackException.NotConnectedException {
Log.d("CheckPacket", "OfflineMEssage");
Message message = (Message) packet;
if (message != null) {
if (message.getBody() != null) {
Log.i("XMPPClient", "Got text [" + message.getBody()
+ "] from [" + message.getFrom() + "]");
}
}
}
}, MESSAGE_PACKET_FILTER);
connection.login(user, password);
Thanks In Advance, Please anybody help me for best working solution for my critical issue.
The issue is in trying to fetch offline messages before
sending the initial presence. XEP-0160 states:
When the recipient next sends non-negative available presence to the server, the server delivers the message to the resource that has sent that presence. [...]
MongooseIM works with accordance to this recommendation.
You already pointed out what is signaled by isFlexibleRetrievalSupport - the server does not support flexible offline message retrieval.
I know I am writing this too late, but if someone like me who is hunting for same query as in "how to save and get archive messages in android app" can refer this answer :
Note :
this is implemented in the lastest version
Requrirements :
lastest openfire as of now 4.1.4
install Archives plugin in openfire
MamManager mamManager = MamManager.getInstanceFor(connection);
boolean isSupported = mamManager.isSupportedByServer();
if (isSupported) {
MamManager.MamQueryResult mamQueryResult = mamManager.queryArchive(500);
List<Forwarded> forwardedMessages = mamQueryResult.forwardedMessages;
Forwarded d = forwardedMessages.get(0);
}
Please Refer : Documention for MamManager Class
I am doing work on GCM (Google Cloud Messaging) in Android. I am looking for the upstream message using GCM.
Code send the GCM messages to cloud here
try {
Bundle data = new Bundle();
// the account is used for keeping
// track of user notifications
data.putString("account", account);
// the action is used to distinguish
// different message types on the server
data.putString("action", Constants.ACTION_REGISTER);
String msgId = Integer.toString(getNextMsgId());
gcm.send(projectId + "#gcm.googleapis.com", msgId,
Constants.GCM_DEFAULT_TTL, data);
} catch (IOException e) {
Log.e("grokkingandroid",
"IOException while sending registration id", e);
}
Now question is that what cloud would do for that upstream message, Where it can be useful in Android and How ??
When you send an upstream message from your app, the GCM Cloud Connection Server (CCS) transfers that message to your server. In order for that to work, you must implement a server that supports XMPP protocol and establishes a TLS connection with GCM Cloud Connection Server. You also need your API project to be white-listed for using this feature. You can read more about it here.
As for usefulness, it allows you to send messages to your app via the GCM connection instead of via your own connection between your app and your server. That's more battery efficient.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "FCM Token creation logic");
// Get variables reference
deviceText = (TextView) findViewById(R.id.deviceText);
editTextEcho = (EditText) findViewById(R.id.editTextEcho);
buttonUpstreamEcho = (Button) findViewById(R.id.buttonUpstreamEcho);
//Get token from Firebase
FirebaseMessaging.getInstance().subscribeToTopic("test");
final String token = FirebaseInstanceId.getInstance().getToken();
Log.d(TAG, "Token: " + token);
deviceText.setText(token);
//Call the token service to save the token in the database
tokenService = new TokenService(this, this);
tokenService.registerTokenInDB(token);
buttonUpstreamEcho.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "Echo Upstream message logic");
String message = editTextEcho.getText().toString();
Log.d(TAG, "Message: " + message + ", recipient: " + token);
FirebaseMessaging.getInstance().send(new RemoteMessage.Builder(FCM_PROJECT_SENDER_ID + FCM_SERVER_CONNECTION)
.setMessageId(Integer.toString(RANDOM.nextInt()))
.addData("message", message)
.addData("action", BACKEND_ACTION_ECHO)
.build());
// To send a message to other device through the XMPP Server, you should add the
// receiverId and change the action name to BACKEND_ACTION_MESSAGE in the data
}
});
}
This is a sample Android project to showcase the Firebase Cloud Messaging (FCM) to manage upstream and downstream messages.
https://github.com/carlosCharz/FCMTest
This is the video in youtube that explains what it does.
https://www.youtube.com/watch?v=SEzOKSoAMG0
Hope you find it useful.
I am using the Amazon Web Service to send push notifications directly to a device. After I install the app I get the device id, that I need to manually add to the Amazon SNS. I would like to know if there is anyway to register the device id directly with the amazon server the moment the user starts the application.
I have read this, but found it difficult to understand. Does anyone have any previous experience of how to do this?
EDIT 2 (What I have done so far)
I've followed the instructions from this link
I download the snspobilepush.zip file as instructed and extract and import the project into eclipse. I add the GCM project number, add the jar files and run the application. I get my device registration Id.
I open the Amazon SNS, add my device id and I publish a message. I receive the message on my mobile phone. Works great so far.
MY PROBLEM
I would be having a lot of potential users for my application. So adding every device id manually to the SNS makes no sense. I need the Amazon SNS to directly register my device id when I start the app. Is there any option for me to do that? I couldn't find any definitive answer in the docs.
This link tells me to Use the "AWS Token Vending Service". However, I could not find any example of how to do that.
Using the AmazonSNSClient documented here:
http://docs.aws.amazon.com/AWSAndroidSDK/latest/javadoc/
it should be possible to register using code similar to this:
AWSCredentials awsCredentials = new BasicAWSCredentials("XXXXXX", "XXXXXXXXXXXXXXX");
String platformApplicationArn = "arn:aws:sns:us-east-1:123456789:app/GCM/myappname";
AmazonSNSClient pushClient = new AmazonSNSClient(awsCredentials);
String customPushData = "my custom data";
CreatePlatformEndpointRequest platformEndpointRequest = new CreatePlatformEndpointRequest();
platformEndpointRequest.setCustomUserData(customPushData);
platformEndpointRequest.setToken(pushNotificationRegId);
platformEndpointRequest.setPlatformApplicationArn(platformApplicationArn);
CreatePlatformEndpointResult result = pushClient.createPlatformEndpoint(platformEndpointRequest);
Log.w(TAG, "Amazon Push reg result: " + result);
It was not liking my ARN, but that was a stupid typo that Reid pointed out and is now fixed above.
There is Android AWS SDK available to use. Check out the documentation link: http://docs.aws.amazon.com/AWSAndroidSDK/latest/javadoc/
Also, more information available: http://aws.amazon.com/sdkforandroid/
This is working for Firebase and Cognito. An AsyncTask is necessary to avoid running on the Main Thread.
private class RegisterIdForAWS extends AsyncTask<String, Void, Void> {
private Exception exception;
protected Void doInBackground(String... urls) {
try {
String pushNotificationRegId = FirebaseInstanceId.getInstance().getToken();
if (pushNotificationRegId != null) {
CognitoCachingCredentialsProvider provider = new CognitoCachingCredentialsProvider(
getApplicationContext(),
"us-west-2:aaaaaaaaa-1234-1234-1234-0bbbbbbbbbbbb",
Regions.US_WEST_2);
String platformApplicationArn = "arn:aws:sns:us-west-2:123456789:app/GCM/appname";
AmazonSNSClient pushClient = new AmazonSNSClient(provider);
pushClient.setRegion(Region.getRegion(Regions.US_WEST_2));
String customPushData = "";
CreatePlatformEndpointRequest platformEndpointRequest = new CreatePlatformEndpointRequest();
platformEndpointRequest.setCustomUserData(customPushData);
platformEndpointRequest.setToken(pushNotificationRegId);
platformEndpointRequest.setPlatformApplicationArn(platformApplicationArn);
CreatePlatformEndpointResult result = pushClient.createPlatformEndpoint(platformEndpointRequest);
Log.w(TAG, "Amazon Push reg result: " + result);
}
} catch (Exception e) {
this.exception = e;
}
return null;
}
protected void onPostExecute(String text) {
Log.w(TAG, "Amazon Push reg Finished");
}
}