亚马逊SNS集成GCM的详细步骤

  • 亚马逊SNS集成GCM的详细步骤
    具体原理自行了解下,本编文章主要讲解步骤

1、在Android studio 的app Builde.gradle下添加SDK

      compile 'com.amazonaws:aws-android-sdk-sns:2.2.18'
      compile 'com.google.android.gms:play-services:9.4.0'

2、清单文件下添加权限 和 配置广播、服务

   <!--app所需权限-->
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
    <uses-permission android:name="android.permission.WAKE_LOCK"/>

    <!--官方文档自带的权限-->
    <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE"/>
    <permission
        android:name="com.amazon.mysampleapp.permission.C2D_MESSAGE"
        android:protectionLevel="signature"/>
    <uses-permission android:name="com.amazon.mysampleapp.permission.C2D_MESSAGE"/>


  <!-- BEGIN - PUSH NOTIFICATIONS WITH GOOGLE CLOUD MESSAGING (GCM) -->
        <receiver
            android:name="com.google.android.gms.gcm.GcmReceiver"
            android:exported="true"
            android:permission="com.google.android.c2dm.permission.SEND">
            <intent-filter>
                <action android:name="com.google.android.c2dm.intent.RECEIVE"/>
                <category android:name="com.testdatabinding"/>
            </intent-filter>
        </receiver>
        <service
            android:name=".service.PushListenerService"
            android:exported="false" >
            <intent-filter>
                <action android:name="com.google.android.c2dm.intent.RECEIVE" />
            </intent-filter>
        </service>

3、点击Activity中的按钮,注册服务,就可以在Amazon AWS后台推送消息了

    public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        AWSMobileClient.initializeMobileClientIfNecessary(getApplicationContext());
        pushManager = AWSMobileClient.defaultMobileClient().getPushManager();
    }

    private PushManager pushManager;

    /**
     * 点击注册消息推送服务
     * @param view
     */
    public void click(View view) {
        toggleNotification(true);
    }

        private void toggleNotification(final boolean enabled) {

        new AsyncTask<Void, Void, String>() {
            @Override
            protected String doInBackground(final Void... params) {
                pushManager.registerDevice();
                if (pushManager.isRegistered()) {
                    try {
                        pushManager.setPushEnabled(enabled);
                        if (enabled) {
                            //获取当前系统语言
                            String language = Locale.getDefault().getLanguage().toUpperCase();
                            //创建包含主题名字的请求
                            CreateTopicRequest topicRequest1 = new CreateTopicRequest(language);
                            CreateTopicRequest topicRequest2 = new CreateTopicRequest("Romwe");
                            CreateTopicRequest topicRequest3 = new CreateTopicRequest("Android");
                            //通过sns创建主题
                            AmazonSNS sns = pushManager.getAmazonSNS();
                            sns.createTopic(topicRequest1);
                            sns.createTopic(topicRequest2);
                            sns.createTopic(topicRequest3);
                            //获取默认前缀
                            String topicArn = pushManager.getDefaultTopic().getTopicArn();
                            String prefixText = topicArn.substring(0, topicArn.lastIndexOf(':') + 1);
                            String[] topics = new String[3];
                            topics[0] = prefixText + language;
                            topics[1] = prefixText + "Romwe";
                            topics[2] = prefixText + "Android";
                            pushManager.setTopics(topics);
                            pushManager.resubscribeToTopics();
                        }
                        return null;
                    } catch (final AmazonClientException ace) {
                        return ace.getMessage();
                    }
                }
                return "Failed to register for push notifications.";
            }

            @Override
            protected void onPostExecute(final String errorMessage) {
                System.out.println((errorMessage == null) ? "订阅成功。。。。。" : "订阅失败。。。。。" + errorMessage);
                if (errorMessage != null) {
                    showErrorMessage(R.string.push_demo_error_message_update_notification,
                            errorMessage);
                }
            }
        }.execute();
    }

    private AlertDialog showErrorMessage(final int resId, final Object... args) {
        return new AlertDialog.Builder(this).setMessage(getString(resId, (Object[]) args))
                .setPositiveButton(android.R.string.ok, null)
                .show();
    }

4、下载Amazon的SDK源码

5、在app项目里创建一个服务在后台接受通知

    public class PushListenerService extends GcmListenerService {

    private static final String LOG_TAG = PushListenerService.class.getSimpleName();

    // Intent action used in local broadcast
    public static final String ACTION_SNS_NOTIFICATION = "sns-notification";
    // Intent keys
    public static final String INTENT_SNS_NOTIFICATION_FROM = "from";
    public static final String INTENT_SNS_NOTIFICATION_DATA = "data";

    /**
     * Helper method to extract SNS message from bundle.
     *
     * @param data bundle
     * @return message string from SNS push notification
     */
    public static String getMessage(Bundle data) {
        // If a push notification is sent as plain text, then the message appears in "default".
        // Otherwise it's in the "message" for JSON format.
        return data.containsKey("default") ? data.getString("default") : data.getString(
            "message", "");
    }

    /**
     * 判断App是否在前台,如果是就弹出一个Dialog,否则在通知栏提示
     */
    private static boolean isForeground(Context context) {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> tasks = am.getRunningAppProcesses();

        final String packageName = context.getPackageName();
        for (ActivityManager.RunningAppProcessInfo appProcess : tasks) {
            if (ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND == appProcess.importance
                && packageName.equals(appProcess.processName)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 在顶部显示通知
     * @param message
     */
    private void displayNotification(final String message) {
        Intent notificationIntent = new Intent(this, MainActivity.class);
        notificationIntent.setFlags(
                Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        int requestID = (int) System.currentTimeMillis();
        PendingIntent contentIntent = PendingIntent.getActivity(this, requestID, notificationIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);

        // Display a notification with an icon, message as content, and default sound. It also
        // opens the app when the notification is clicked.
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this).setSmallIcon(
                R.mipmap.push)
                .setContentTitle(getString(R.string.push_demo_title))
                .setContentText(message)
                .setDefaults(Notification.DEFAULT_SOUND)
                .setAutoCancel(true)
                .setContentIntent(contentIntent);

        NotificationManager notificationManager = (NotificationManager) getSystemService(
                Context.NOTIFICATION_SERVICE);

        notificationManager.notify(0, builder.build());
    }

    private void broadcast(final String from, final Bundle data) {
        Intent intent = new Intent(ACTION_SNS_NOTIFICATION);
        intent.putExtra(INTENT_SNS_NOTIFICATION_FROM, from);
        intent.putExtra(INTENT_SNS_NOTIFICATION_DATA, data);
        LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
    }

    /**
     *当接收到推送消息时  Todo 这里处理逻辑
     */
    @Override
    public void onMessageReceived(final String from, final Bundle data) {
        String message = getMessage(data);
        Log.d(LOG_TAG, "From: " + from);
        Log.d(LOG_TAG, "Message: " + message);
        displayNotification(message);
//        if (isForeground(this)) {
//            // broadcast notification
//            broadcast(from, data);
//        } else {
//            displayNotification(message);
//        }
    }
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值