简体   繁体   English

AWS Pinpoint - 如何在程序中设置推送通知

[英]AWS Pinpoint - How to set up push notifications in the program

In the company I work, I was asked to make some tests with AWS's new service of push notifications, the Amazon Pinpoint. 在我工作的公司中,我被要求使用AWS的推送通知新服务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. 问题是,我从来没有用Java编程,所以,在这之后 ,我陷入了最后一步。 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! 谢谢!

It is recommended to create the PinpointManager object in the Application class upon app startup. 建议在应用程序启动时在Application类中创建PinpointManager对象。 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. 以下示例使用AWSConfiguration ,该文件是从应用程序的res / raw文件夹中的Amplify CLI创建的awsconfiguration.json文件中读取的。

You can retrieve the token from the service onNewToken callback method and register the token with the Pinpoint NotificationClient. 您可以从服务onNewToken回调方法中检索令牌,并使用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. 您需要在AndroidManifest.xml中注册MyApplication类。

To receive the push notifications, assuming you are using FCM, you need to create a service as follows: 要接收推送通知,假设您使用的是FCM,则需要按如下方式创建服务:

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: 现在,我的MainActivity看起来如下:

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. 请在评论中发布任何澄清问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM