Reputation: 1438
In the company I work, I was asked to make some tests with AWS's new service of push notifications, the Amazon Pinpoint.
I decided to follow a tutorial from Amazon, teaching how to build a simple app capable of recording notes. It was easy and worked perfectly, so I decided to move on and teach my new simple program to receive push notifications.
The problem is, I never programmed in Java, so, while following this, I got stuck in the last step. I am really unsure about where to put this part of the code:
import com.amazonaws.mobileconnectors.pinpoint.PinpointConfiguration;
import com.amazonaws.mobileconnectors.pinpoint.PinpointManager;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import com.google.android.gms.iid.InstanceID;
public class MainActivity extends AppCompatActivity {
public static final String LOG_TAG = MainActivity.class.getSimpleName();
public static PinpointManager pinpointManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (pinpointManager == null) {
PinpointConfiguration pinpointConfig = new PinpointConfiguration(
getApplicationContext(),
AWSMobileClient.getInstance().getCredentialsProvider(),
AWSMobileClient.getInstance().getConfiguration());
pinpointManager = new PinpointManager(pinpointConfig);
new Thread(new Runnable() {
@Override
public void run() {
try {
String deviceToken =
InstanceID.getInstance(MainActivity.this).getToken(
"123456789Your_GCM_Sender_Id",
GoogleCloudMessaging.INSTANCE_ID_SCOPE);
Log.e("NotError", deviceToken);
pinpointManager.getNotificationClient()
.registerGCMDeviceToken(deviceToken);
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
}
}
I know the question ended up really generic, but I have no other idea about how to ask it. If anything, just ask me for more info. Thanks!
Upvotes: 3
Views: 2001
Reputation: 1441
It is recommended to create the PinpointManager object in the Application class upon app startup. The following example uses AWSConfiguration
which is read from awsconfiguration.json
file created by the Amplify CLI in the res/raw folder of your app.
You can retrieve the token from the service onNewToken
callback method and register the token with the Pinpoint NotificationClient.
public class MyApplication extends Application {
private static final String LOG_TAG = MyApplication.class.getSimpleName();
public static PinpointManager pinpointManager;
@Override
public void onCreate() {
super.onCreate();
AWSConfiguration awsConfiguration = new AWSConfiguration(this);
PinpointConfiguration pinpointConfiguration = new PinpointConfiguration(this,
new CognitoCachingCredentialsProvider(this, awsConfiguration),
awsConfiguration);
pinpointManager = new PinpointManager(pinpointConfiguration);
}
}
You need to register the MyApplication
class in your AndroidManifest.xml.
To receive the push notifications, assuming you are using FCM, you need to create a service as follows:
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import com.amazonaws.mobileconnectors.pinpoint.targeting.notification.NotificationClient;
import com.amazonaws.mobileconnectors.pinpoint.targeting.notification.NotificationDetails;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;
import java.util.HashMap;
public class PushListenerService extends FirebaseMessagingService {
public static final String TAG = PushListenerService.class.getSimpleName();
// Intent action used in local broadcast
public static final String ACTION_PUSH_NOTIFICATION = "push-notification";
// Intent keys
public static final String INTENT_SNS_NOTIFICATION_FROM = "from";
public static final String INTENT_SNS_NOTIFICATION_DATA = "data";
@Override
public void onNewToken(String token) {
super.onNewToken(token);
Log.d(TAG, "Registering push notifications token: " + token);
MyApplication.pinpointManager.getNotificationClient().registerDeviceToken(token);
}
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
Log.d(TAG, "from: " + remoteMessage.getFrom());
Log.d(TAG, "Message: " + remoteMessage.getData());
final NotificationDetails notificationDetails = NotificationDetails.builder()
.from(remoteMessage.getFrom())
.mapData(remoteMessage.getData())
.intentAction(NotificationClient.FCM_INTENT_ACTION)
.build();
final NotificationClient notificationClient = MyApplication.pinpointManager.getNotificationClient();
NotificationClient.CampaignPushResult pushResult = notificationClient.handleCampaignPush(notificationDetails);
if (!NotificationClient.CampaignPushResult.NOT_HANDLED.equals(pushResult)) {
/**
The push message was due to a Pinpoint campaign.
If the app was in the background, a local notification was added
in the notification center. If the app was in the foreground, an
event was recorded indicating the app was in the foreground,
for the demo, we will broadcast the notification to let the main
activity display it in a dialog.
*/
if (NotificationClient.CampaignPushResult.APP_IN_FOREGROUND.equals(pushResult)) {
/* Create a message that will display the raw data of the campaign push in a dialog. */
final HashMap<String, String> dataMap = new HashMap<String, String>(remoteMessage.getData());
broadcast(remoteMessage.getFrom(), dataMap);
}
return;
}
}
private void broadcast(final String from, final HashMap<String, String> dataMap) {
Intent intent = new Intent(ACTION_PUSH_NOTIFICATION);
intent.putExtra(INTENT_SNS_NOTIFICATION_FROM, from);
intent.putExtra(INTENT_SNS_NOTIFICATION_DATA, dataMap);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
/**
* Helper method to extract push message from bundle.
*
* @param data bundle
* @return message string from push notification
*/
public static String getMessage(Bundle data) {
return ((HashMap) data.get("data")).toString();
}
}
Now, My MainActivity looks as follows:
import android.app.Application;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import com.amazonaws.mobileconnectors.pinpoint.PinpointManager;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.iid.InstanceIdResult;
import java.util.HashMap;
public class MainActivity extends AppCompatActivity {
public static final String TAG = MainActivity.class.getSimpleName();
private static PinpointManager pinpointManager;
public static PinpointManager getPinpointManager(final Context applicationContext) {
if (pinpointManager == null) {
pinpointManager = MyApplication.pinpointManager;
FirebaseInstanceId.getInstance().getInstanceId()
.addOnCompleteListener(new OnCompleteListener<InstanceIdResult>() {
@Override
public void onComplete(@NonNull Task<InstanceIdResult> task) {
final String token = task.getResult().getToken();
Log.d(TAG, "Registering push notifications token: " + token);
pinpointManager.getNotificationClient().registerDeviceToken(token);
}
});
}
return pinpointManager;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
// Initialize PinpointManager
getPinpointManager(getApplicationContext());
LocalBroadcastManager
.getInstance(this)
.registerReceiver(new PushNotificationBroadcastReceiver(),
new IntentFilter(PushListenerService.ACTION_PUSH_NOTIFICATION));
Log.d(TAG, "Endpoint-id: " +
pinpointManager.getTargetingClient().currentEndpoint().getEndpointId());
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
// no inspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private class PushNotificationBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String data = ((HashMap<String, String>) intent.getSerializableExtra(PushListenerService.INTENT_SNS_NOTIFICATION_DATA)).toString();
Toast.makeText(context, "from: " + intent.getStringExtra(PushListenerService.INTENT_SNS_NOTIFICATION_FROM), Toast.LENGTH_LONG).show();
Toast.makeText(context, "data: " + data , Toast.LENGTH_LONG).show();
}
}
}
Please post any clarifications questions in the comment.
Upvotes: 5