gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 04:18:04 25 4
gpt4 key购买 nike

在我工作的公司,我被要求使用 AWS 的新推送通知服务 Amazon Pinpoint 进行一些测试。

我决定跟随 Amazon 的 a tutorial,教授如何构建一个能够记录笔记的简单应用程序。这很简单,而且效果很好,所以我决定继续学习我的新简单程序来接收推送通知。

问题是,我从来没有用 Java 编程过,所以,在遵循 this 时,我卡在了最后一步。我真的不确定将这部分代码放在哪里:

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

我知道这个问题最终很笼统,但我对如何提出这个问题一无所知。如果有的话,请向我询问更多信息。谢谢!

最佳答案

建议在应用程序启动时在 Application 类中创建 PinpointManager 对象。以下示例使用 AWSConfiguration,它是从 Amplify CLI 在您的应用程序的 res/raw 文件夹中创建的 awsconfiguration.json 文件中读取的。

您可以从服务 onNewToken 回调方法中检索 token ,并使用 Pinpoint NotificationClient 注册 token 。

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

您需要在 AndroidManifest.xml 中注册 MyApplication 类。

要接收推送通知,假设您使用的是 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();
}
}

现在,我的 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();
}
}
}

请在评论中提出任何需要澄清的问题。

关于java - AWS Pinpoint - 如何在程序中设置推送通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51050483/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com