AWS Pinpoint - как настроить push-уведомления в программе - PullRequest
0 голосов
/ 26 июня 2018

В компании, в которой я работаю, меня попросили провести несколько тестов с новым сервисом push-уведомлений AWS - Amazon Pinpoint.

Я решил последовать учебнику от Amazon, обучающему созданию простого приложения, способного записывать заметки. Это было легко и отлично работало, поэтому я решил пойти дальше и научить свою новую простую программу получать push-уведомления.

Проблема в том, что я никогда не программировал на Java, поэтому, следуя этому , я застрял на последнем шаге. Я действительно не уверен, где разместить эту часть кода:

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();
         }
     }
 }

Я знаю, что вопрос оказался действительно общим, но я понятия не имею, как его задать. Если что, просто спросите меня для получения дополнительной информации. Спасибо!

1 Ответ

0 голосов
/ 30 октября 2018

Рекомендуется создать объект PinpointManager в классе Application при запуске приложения. В следующем примере используется AWSConfiguration, который читается из файла awsconfiguration.json, созданного с помощью интерфейса командной строки Amplify в папке res / raw вашего приложения.

Вы можете получить токен из метода обратного вызова службы 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);
    }
}

Вам необходимо зарегистрировать класс MyApplication в вашем AndroidManifest.xml.

Чтобы получать push-уведомления, при условии, что вы используете 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();
    }
}

Теперь My 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();
        }
    }
}

Пожалуйста, оставляйте любые уточняющие вопросы в комментарии.

...