AmazonSNS - AwsCredentials.properties - NullPointerException

时间:2015-08-19 15:06:31

标签: android amazon-web-services intellij-idea amazon-sns

我是Android Studio和intelliJ的新手。

我正在尝试使用AmazonSNS - 推送。我无法弄清楚如何将AwsCredentials.properties文件添加到模块的类路径中。我在下图中的第57行得到了一个N​​PE(在方法getResourceAsStream()处)。我在AwsCredentials.properties文件中添加了所需的密钥。

enter image description here

错误:

enter image description here

在我在StackOverflow上遇到的有关类似问题的问题中,有人建议该文件应该在根文件夹中,其中,src是。我将它放在与src相同的文件夹中,但仍然获得了NPE。我也尝试将文件放在com / test /中,但没有用。

我该如何解决这个问题?还有其他步骤吗?

启动赏金后编辑 - 添加java文件

这是我到现在为止所做的事情。

  1. 创建一个名为MyApplication的Android应用程序。从演示应用程序导入所有类(AndroidMobilePushApp.java,ExternalReceiver.java,MessageReceivingService.java)。添加了必需的库,并运行它并将注册表ID作为亚马逊的响应。

  2. 在同一个应用程序中,我创建了一个名为snspush的新模块,并将SNSMobilePush.java文件导入其中。还将AwsCredentials.properties文件导入到与SNSMobilePush.java相同的路径中。添加了AwsCredentials.properties文件中的密钥。

  3. 按照文档中的步骤取消注释必要的功能。

  4. 项目结构:

    enter image description here

    Java文件:

    1. AndroidMobilePushApp.java:

      public class AndroidMobilePushApp扩展AppCompatActivity {     私有TextView tView;     private SharedPreferences savedValues;     private String numOfMissedMessages;

      // Since this activity is SingleTop, there can only ever be one instance. This variable corresponds to this instance.
      public static Boolean inBackground = true;
      
      public void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          numOfMissedMessages = getString(R.string.num_of_missed_messages);
          setContentView(R.layout.activity_main);
          tView = (TextView) findViewById(R.id.tViewId);
          tView.setMovementMethod(new ScrollingMovementMethod());
          startService(new Intent(this, MessageReceivingService.class));
      }
      
      public void onStop(){
          super.onStop();
          inBackground = true;
      }
      
      public void onRestart(){
          super.onRestart();
          tView.setText("");;
      }
      
      public void onResume(){
          super.onResume();
          inBackground = false;
          savedValues = MessageReceivingService.savedValues;
          int numOfMissedMessages = 0;
          if(savedValues != null){
              numOfMissedMessages = savedValues.getInt(this.numOfMissedMessages, 0);
          }
          String newMessage = getMessage(numOfMissedMessages);
          if(newMessage!=""){
              Log.i("displaying message", newMessage);
              tView.append(newMessage);
          }
      }
      
      public void onNewIntent(Intent intent){
          super.onNewIntent(intent);
          setIntent(intent);
      }
      
      // If messages have been missed, check the backlog. Otherwise check the current intent for a new message.
      private String getMessage(int numOfMissedMessages) {
          String message = "";
          String linesOfMessageCount = getString(R.string.lines_of_message_count);
          if(numOfMissedMessages > 0){
              String plural = numOfMissedMessages > 1 ? "s" : "";
              Log.i("onResume","missed " + numOfMissedMessages + " message" + plural);
              tView.append("You missed " + numOfMissedMessages +" message" + plural + ". Your most recent was:\n");
              for(int i = 0; i < savedValues.getInt(linesOfMessageCount, 0); i++){
                  String line = savedValues.getString("MessageLine"+i, "");
                  message+= (line + "\n");
              }
              NotificationManager mNotification = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
              mNotification.cancel(R.string.notification_number);
              SharedPreferences.Editor editor=savedValues.edit();
              editor.putInt(this.numOfMissedMessages, 0);
              editor.putInt(linesOfMessageCount, 0);
              editor.commit();
          }
          else{
              Log.i("onResume","no missed messages");
              Intent intent = getIntent();
              if(intent!=null){
                  Bundle extras = intent.getExtras();
                  if(extras!=null){
                      for(String key: extras.keySet()){
                          message+= key + "=" + extras.getString(key) + "\n";
                      }
                  }
              }
          }
          message+="\n";
          return message;
      }
      
      public boolean onCreateOptionsMenu(Menu menu) {
          // Inflate the menu; this adds items to the action bar if it is present.
          getMenuInflater().inflate(R.menu.main, menu);
          return true;
      }
      
      public boolean onOptionsItemSelected(MenuItem item) {
          if(item.getItemId() == R.id.menu_clear){
              tView.setText("");
              return true;
          }
          else{
              return super.onOptionsItemSelected(item);
          }
      }
      

      }

    2. ExternalReceiver.java

      package com.test.awstestapp;

      import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.os.Bundle;

      公共类ExternalReceiver扩展了BroadcastReceiver {

      public void onReceive(Context context, Intent intent) {
          if(intent!=null){
              Bundle extras = intent.getExtras();
              if(!AndroidMobilePushApp.inBackground){
                  MessageReceivingService.sendToApp(extras, context);
              }
              else{
                  MessageReceivingService.saveToLog(extras, context);
              }
          }
      }
      

      }

    3. MessageReceivingService.java

    4. 公共类MessageReceivingService扩展Service {     私有GoogleCloudMessaging gcm;     public static SharedPreferences savedValues;

      public static void sendToApp(Bundle extras, Context context){
          Intent newIntent = new Intent();
          newIntent.setClass(context, AndroidMobilePushApp.class);
          newIntent.putExtras(extras);
          newIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
          context.startActivity(newIntent);
      }
      
      public void onCreate(){
          super.onCreate();
          final String preferences = getString(R.string.preferences);
          savedValues = getSharedPreferences(preferences, Context.MODE_PRIVATE);
          // In later versions multi_process is no longer the default
          if(VERSION.SDK_INT >  9){
              savedValues = getSharedPreferences(preferences, Context.MODE_MULTI_PROCESS);
          }
          gcm = GoogleCloudMessaging.getInstance(getBaseContext());
          SharedPreferences savedValues = PreferenceManager.getDefaultSharedPreferences(this);
          if(savedValues.getBoolean(getString(R.string.first_launch), true)){
              register();
              SharedPreferences.Editor editor = savedValues.edit();
              editor.putBoolean(getString(R.string.first_launch), false);
              editor.commit();
          }
          // Let AndroidMobilePushApp know we have just initialized and there may be stored messages
          sendToApp(new Bundle(), this);
      }
      
      protected static void saveToLog(Bundle extras, Context context){
          SharedPreferences.Editor editor=savedValues.edit();
          String numOfMissedMessages = context.getString(R.string.num_of_missed_messages);
          int linesOfMessageCount = 0;
          for(String key : extras.keySet()){
              String line = String.format("%s=%s", key, extras.getString(key));
              editor.putString("MessageLine" + linesOfMessageCount, line);
              linesOfMessageCount++;
          }
          editor.putInt(context.getString(R.string.lines_of_message_count), linesOfMessageCount);
          editor.putInt(context.getString(R.string.lines_of_message_count), linesOfMessageCount);
          editor.putInt(numOfMissedMessages, savedValues.getInt(numOfMissedMessages, 0) + 1);
          editor.commit();
          postNotification(new Intent(context, AndroidMobilePushApp.class), context);
      }
      
      protected static void postNotification(Intent intentAction, Context context){
          final NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
      
          final PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intentAction, Notification.DEFAULT_LIGHTS | Notification.FLAG_AUTO_CANCEL);
          final Notification notification = new NotificationCompat.Builder(context).setSmallIcon(R.mipmap.ic_launcher)
                  .setContentTitle("Message Received!")
                  .setContentText("")
                  .setContentIntent(pendingIntent)
                  .setAutoCancel(true)
                  .getNotification();
      
          mNotificationManager.notify(R.string.notification_number, notification);
      }
      
      private void register() {
          new AsyncTask(){
              protected Object doInBackground(final Object... params) {
                  String token;
                  try {
                      token = gcm.register(getString(R.string.project_number));
                      Log.i("registrationId", token);
                  } 
                  catch (IOException e) {
                      Log.i("Registration Error", e.getMessage());
                  }
                  return true;
              }
          }.execute(null, null, null);
      }
      
      public IBinder onBind(Intent arg0) {
          return null;
      }
      

      }

      SNSMobilePush.java

      package com.test;

      public class SNSMobilePush {
      
          private AmazonSNSClientWrapper snsClientWrapper;
      
          public SNSMobilePush(AmazonSNS snsClient) {
              this.snsClientWrapper = new AmazonSNSClientWrapper(snsClient);
          }
      
          public static final Map<Platform, Map<String, MessageAttributeValue>> attributesMap = new HashMap<Platform, Map<String, MessageAttributeValue>>();
          static {
              attributesMap.put(Platform.ADM, null);
              attributesMap.put(Platform.GCM, null);
              attributesMap.put(Platform.APNS, null);
              attributesMap.put(Platform.APNS_SANDBOX, null);
              attributesMap.put(Platform.BAIDU, addBaiduNotificationAttributes());
              attributesMap.put(Platform.WNS, addWNSNotificationAttributes());
              attributesMap.put(Platform.MPNS, addMPNSNotificationAttributes());
          }
      
          public static void main(String[] args) throws IOException {
              /*
               * TODO: Be sure to fill in your AWS access credentials in the
               * AwsCredentials.properties file before you try to run this sample.
               * http://aws.amazon.com/security-credentials
               */
              AmazonSNS sns = new AmazonSNSClient(new PropertiesCredentials(
                      SNSMobilePush.class
                              .getResourceAsStream("AwsCredentials.properties")));
      
              sns.setEndpoint("https://sns.us-west-2.amazonaws.com");
              System.out.println("===========================================\n");
              System.out.println("Getting Started with Amazon SNS");
              System.out.println("===========================================\n");
              try {
                  SNSMobilePush sample = new SNSMobilePush(sns);
                  /* TODO: Uncomment the services you wish to use. */
                  sample.demoAndroidAppNotification();
                  // sample.demoKindleAppNotification();
                  // sample.demoAppleAppNotification();
                  // sample.demoAppleSandboxAppNotification();
                  // sample.demoBaiduAppNotification();
                  // sample.demoWNSAppNotification();
                  // sample.demoMPNSAppNotification();
              } catch (AmazonServiceException ase) {
                  System.out
                          .println("Caught an AmazonServiceException, which means your request made it "
                                  + "to Amazon SNS, but was rejected with an error response for some reason.");
                  System.out.println("Error Message:    " + ase.getMessage());
                  System.out.println("HTTP Status Code: " + ase.getStatusCode());
                  System.out.println("AWS Error Code:   " + ase.getErrorCode());
                  System.out.println("Error Type:       " + ase.getErrorType());
                  System.out.println("Request ID:       " + ase.getRequestId());
              } catch (AmazonClientException ace) {
                  System.out
                          .println("Caught an AmazonClientException, which means the client encountered "
                                  + "a serious internal problem while trying to communicate with SNS, such as not "
                                  + "being able to access the network.");
                  System.out.println("Error Message: " + ace.getMessage());
              }
          }
      
          public void demoAndroidAppNotification() {
              // TODO: Please fill in following values for your application. You can
              // also change the notification payload as per your preferences using
              // the method
              // com.amazonaws.sns.samples.tools.SampleMessageGenerator.getSampleAndroidMessage()
              String serverAPIKey = "REPLACED_WITH_SERVER_API_KEY";
              String applicationName = "snspushtest";
              String registrationId = "REPLACED_WITH_REG_ID_FROM_AMAZON";
              snsClientWrapper.demoNotification(Platform.GCM, "", serverAPIKey,
                      registrationId, applicationName, attributesMap);
          }
      
          public void demoKindleAppNotification() {
              // TODO: Please fill in following values for your application. You can
              // also change the notification payload as per your preferences using
              // the method
              // com.amazonaws.sns.samples.tools.SampleMessageGenerator.getSampleKindleMessage()
              String clientId = "";
              String clientSecret = "";
              String applicationName = "";
      
              String registrationId = "";
              snsClientWrapper.demoNotification(Platform.ADM, clientId, clientSecret,
                      registrationId, applicationName, attributesMap);
          }
      
          public void demoAppleAppNotification() {
              // TODO: Please fill in following values for your application. You can
              // also change the notification payload as per your preferences using
              // the method
              // com.amazonaws.sns.samples.tools.SampleMessageGenerator.getSampleAppleMessage()
              String certificate = ""; // This should be in pem format with \n at the
                                          // end of each line.
              String privateKey = ""; // This should be in pem format with \n at the
                                      // end of each line.
              String applicationName = "";
              String deviceToken = ""; // This is 64 hex characters.
              snsClientWrapper.demoNotification(Platform.APNS, certificate,
                      privateKey, deviceToken, applicationName, attributesMap);
          }
      
          public void demoAppleSandboxAppNotification() {
              // TODO: Please fill in following values for your application. You can
              // also change the notification payload as per your preferences using
              // the method
              // com.amazonaws.sns.samples.tools.SampleMessageGenerator.getSampleAppleMessage()
              String certificate = ""; // This should be in pem format with \n at the
                                          // end of each line.
              String privateKey = ""; // This should be in pem format with \n at the
                                      // end of each line.
              String applicationName = "";
              String deviceToken = ""; // This is 64 hex characters.
              snsClientWrapper.demoNotification(Platform.APNS_SANDBOX, certificate,
                      privateKey, deviceToken, applicationName, attributesMap);
          }
      
          public void demoBaiduAppNotification() {
              /*
               * TODO: Please fill in the following values for your application. If
               * you wish to change the properties of your Baidu notification, you can
               * do so by modifying the attribute values in the method
               * addBaiduNotificationAttributes() . You can also change the
               * notification payload as per your preferences using the method
               * com.amazonaws
               * .sns.samples.tools.SampleMessageGenerator.getSampleBaiduMessage()
               */
              String userId = "";
              String channelId = "";
              String apiKey = "";
              String secretKey = "";
              String applicationName = "";
              snsClientWrapper.demoNotification(Platform.BAIDU, apiKey, secretKey,
                      channelId + "|" + userId, applicationName, attributesMap);
          }
      
          public void demoWNSAppNotification() {
              /*
               * TODO: Please fill in the following values for your application. If
               * you wish to change the properties of your WNS notification, you can
               * do so by modifying the attribute values in the method
               * addWNSNotificationAttributes() . You can also change the notification
               * payload as per your preferences using the method
               * com.amazonaws.sns.samples
               * .tools.SampleMessageGenerator.getSampleWNSMessage()
               */
              String notificationChannelURI = "";
              String packageSecurityIdentifier = "";
              String secretKey = "";
              String applicationName = "";
              snsClientWrapper.demoNotification(Platform.WNS,
                      packageSecurityIdentifier, secretKey, notificationChannelURI,
                      applicationName, attributesMap);
          }
      
          public void demoMPNSAppNotification() {
              /*
               * TODO: Please fill in the following values for your application. If
               * you wish to change the properties of your MPNS notification, you can
               * do so by modifying the attribute values in the method
               * addMPNSNotificationAttributes() . You can also change the
               * notification payload as per your preferences using the method
               * com.amazonaws
               * .sns.samples.tools.SampleMessageGenerator.getSampleMPNSMessage ()
               */
              String notificationChannelURI = "";
              String applicationName = "";
              snsClientWrapper.demoNotification(Platform.MPNS, "", "",
                      notificationChannelURI, applicationName, attributesMap);
          }
      
          private static Map<String, MessageAttributeValue> addBaiduNotificationAttributes() {
              Map<String, MessageAttributeValue> notificationAttributes = new HashMap<String, MessageAttributeValue>();
              notificationAttributes.put("AWS.SNS.MOBILE.BAIDU.DeployStatus",
                      new MessageAttributeValue().withDataType("String")
                              .withStringValue("1"));
              notificationAttributes.put("AWS.SNS.MOBILE.BAIDU.MessageKey",
                      new MessageAttributeValue().withDataType("String")
                              .withStringValue("default-channel-msg-key"));
              notificationAttributes.put("AWS.SNS.MOBILE.BAIDU.MessageType",
                      new MessageAttributeValue().withDataType("String")
                              .withStringValue("0"));
              return notificationAttributes;
          }
      
          private static Map<String, MessageAttributeValue> addWNSNotificationAttributes() {
              Map<String, MessageAttributeValue> notificationAttributes = new HashMap<String, MessageAttributeValue>();
              notificationAttributes.put("AWS.SNS.MOBILE.WNS.CachePolicy",
                      new MessageAttributeValue().withDataType("String")
                              .withStringValue("cache"));
              notificationAttributes.put("AWS.SNS.MOBILE.WNS.Type",
                      new MessageAttributeValue().withDataType("String")
                              .withStringValue("wns/badge"));
              return notificationAttributes;
          }
      
          private static Map<String, MessageAttributeValue> addMPNSNotificationAttributes() {
              Map<String, MessageAttributeValue> notificationAttributes = new HashMap<String, MessageAttributeValue>();
              notificationAttributes.put("AWS.SNS.MOBILE.MPNS.Type",
                      new MessageAttributeValue().withDataType("String")
                              .withStringValue("token")); // This attribute is required.
              notificationAttributes.put("AWS.SNS.MOBILE.MPNS.NotificationClass",
                      new MessageAttributeValue().withDataType("String")
                              .withStringValue("realtime")); // This attribute is required.
      
              return notificationAttributes;
          }
      }
      

      编辑2:

      enter image description here

      编辑3:

      我将以下代码更改为:

      AmazonSNS sns = new AmazonSNSClient(new PropertiesCredentials(
              SNSMobilePush.class
                      .getResourceAsStream("AwsCredentials.properties")));
      

      AmazonSNS sns = new AmazonSNSClient(new BasicAWSCredentials("ACCESS_KEY_REPLACED",
                      "SECRET_KEY_REPLACED"));
      

      现在,有一个不同的错误:Logcat

      ===========================================
      
      Getting Started with Amazon SNS
      ===========================================
      
      Exception in thread "main" java.lang.NoClassDefFoundError: org/xmlpull/v1/XmlPullParserException
          at com.amazonaws.services.sns.AmazonSNSClient.invoke(AmazonSNSClient.java:2263)
          at com.amazonaws.services.sns.AmazonSNSClient.createPlatformApplication(AmazonSNSClient.java:358)
          at com.test.tools.AmazonSNSClientWrapper.createPlatformApplication(AmazonSNSClientWrapper.java:49)
          at com.test.tools.AmazonSNSClientWrapper.demoNotification(AmazonSNSClientWrapper.java:119)
          at com.test.SNSMobilePush.demoAndroidAppNotification(SNSMobilePush.java:104)
          at com.test.SNSMobilePush.main(SNSMobilePush.java:71)
          at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
          at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
          at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
          at java.lang.reflect.Method.invoke(Method.java:483)
          at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140)
      Caused by: java.lang.ClassNotFoundException: org.xmlpull.v1.XmlPullParserException
          at java.net.URLClassLoader$1.run(URLClassLoader.java:372)
          at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
          at java.security.AccessController.doPrivileged(Native Method)
          at java.net.URLClassLoader.findClass(URLClassLoader.java:360)
          at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
          at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
          at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
          ... 11 more
      
      Process finished with exit code 1
      

3 个答案:

答案 0 :(得分:1)

关于属性凭据

一个。您确定要在构建中导出文件吗?您是否确保可以使用凭据提供程序之外的常规文件I / O访问该文件?您确定文件格式正确(请参阅https://github.com/aws/aws-sdk-android/blob/master/aws-android-sdk-core/src/main/java/com/amazonaws/auth/PropertiesCredentials.java) ACCESSKEY = KEY 秘密密钥= SECRET 另外,查看源代码,您应该可以使用http://developer.android.com/reference/java/util/Properties.html自行加载此文件。

但是,我强烈建议不要使用此凭据提供程序。它在移动应用程序中极不安全。任何人都可以反编译您的应用并窃取您的凭据。一种更安全的方法是使用Amazon Cognito,其中有很多例子。 (https://docs.aws.amazon.com/mobile/sdkforandroid/developerguide/setup.html的底部,此处的任何示例:https://docs.aws.amazon.com/mobile/sdkforandroid/developerguide/getting-started-android.html以及GitHub回购中的示例https://github.com/awslabs/aws-sdk-android-samples

Cognito需要进行一些设置,但会对指南进行测试,而且实际上并不需要花费几分钟时间才能更加安全。

答案 1 :(得分:1)

我正在使用sns v2.2.5:

build.gradle > compile 'com.amazonaws:aws-android-sdk-sns:2.2.5'

这是我的订阅/取消订阅解决方案:

public class AmazonPushClient {

private static final String TAG = "AmazonPushClient";

private static final String PLATFORM_APPLICATION_ARN = "*****";
private static final String IDENTITY_POOL_ID = "******";

private AmazonSNSClient mClient;
private boolean isUnregistering;
private Application mApp;
private NotifPreferencesHelper mNotifPreferencesHelper;

public AmazonPushClient(Application application) {
    try {
        mApp = application;
        mClient = createPushClient(application);
        mNotifPreferencesHelper = new NotifPreferencesHelper(application);
    } catch (Exception e) {
        LOGE(TAG, "AmazonPushClient", e);
    }
}

@Nullable
private String token() {
    try {
        return InstanceID.getInstance(mApp).getToken(mApp.getString(R.string.gcm_defaultSenderId),
                GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
    } catch (Exception e) {
        LOGW(TAG, "token", e);
        return null;
    }
}

private CognitoCachingCredentialsProvider cognitoCachingCredentialsProvider(Application application) {
    return new CognitoCachingCredentialsProvider(
            application,
            IDENTITY_POOL_ID,
            Regions.EU_WEST_1 // if your identity_pool_id start with : eu-west-1
    );
}

private AmazonSNSClient createPushClient(Application application) {
    AmazonSNSClient client = new AmazonSNSClient(cognitoCachingCredentialsProvider(application));
    client.setRegion(Region.getRegion(Regions.EU_WEST_1));
    client.addRequestHandler(mHandler);
    return client;
}

public void pRegister() {
    synchronized (TAG) {
        LOGD(TAG, "registering");
        isUnregistering = true;
        String token = token();
        if(TextUtils.isEmpty(token)) {
            return;
        }
        mNotifPreferencesHelper.saveNotificationPreferences(true);
        CreatePlatformEndpointRequest platformEndpointRequest = new CreatePlatformEndpointRequest();
        platformEndpointRequest.setToken(token());
        platformEndpointRequest.setPlatformApplicationArn(PLATFORM_APPLICATION_ARN);
        CreatePlatformEndpointResult result = mClient.createPlatformEndpoint(platformEndpointRequest);
        mNotifPreferencesHelper.storeEndpointArn(result.getEndpointArn());
    }
}

public void pUnregister() {
    synchronized (TAG) {
        LOGD(TAG, "unregistering");
        isUnregistering = false;
        mNotifPreferencesHelper.saveNotificationPreferences(false);
        DeleteEndpointRequest deletePlatformApplicationRequest = new DeleteEndpointRequest();
        deletePlatformApplicationRequest.setEndpointArn(mNotifPreferencesHelper.getEndpointArn());
        mClient.deleteEndpoint(deletePlatformApplicationRequest);
    }
}

private RequestHandler2 mHandler = new RequestHandler2() {
    @Override
    public void beforeRequest(Request<?> request) {

    }

    @Override
    public void afterResponse(Request<?> request, Response<?> response) {
        if (isUnregistering) {
            mNotifPreferencesHelper.storeEndpointArn(null);
        }
    }

    @Override
    public void afterError(Request<?> request, Response<?> response, Exception e) {
    }
};

}

NotifPreferencesHelper只是存储EndpointARN的东西。您必须在后台线程中使用此类

在关联中你必须实现GcmListenerService等.SNS只是用于订阅而不是接收。 https://developers.google.com/cloud-messaging/

答案 2 :(得分:0)

不要认为你应该将'SNSMobilePush'导入你的Android应用程序的模块

  

在同一个应用程序中,我创建了一个名为snspush的新模块   将SNSMobilePush.java文件导入其中。还进口了   AwsCredentials.properties文件的路径与之相同   SNSMobilePush.java。在AwsCredentials.properties文件中添加了密钥。

SNSMobilePush只是AWS提供的用于执行

等任务的Java应用程序
  • 将几个令牌(设备令牌或注册ID)上传(bulkupload包)到Amazon SNS或

  • 发送推送通知。

您需要向AWS注册您的移动应用程序(使用AndroidMobilePushApp Android应用程序)。您应该获得以下信息(参考this链接)

  • 客户端ID和客户端密钥

  • API密钥

  • 设备令牌或注册ID(每台设备)

然后您可以按照here所述使用SNSMobilePush java app或AWS SNS控制台向您注册的设备发送推送通知。

我建议你尝试从控制台而不是java app发送推送通知。您可以在将来安装应用程序的设备中注册令牌,如上所述here

中的一个选项(最好是最后一个选项)中所述