2016-09-08 1 views
0

AWS SNS를 사용하여 푸시 알림을받는 Android 앱을 개발 중입니다. 기본 흐름은 subscribe id, subscribe secret key, api.i에서 구독 할 주제를 제공 받고 제공된 플랫폼 응용 프로그램 ARN을 사용하여 끝점을 만들고 해당 항목에 가입합니다.AWS SNS를 사용하여 푸시 알림을 수신하지 않음 android

내 코드입니다 : 그 주제와 관련된 푸시 알림이 수신되지 않는 경우입니다

AmazonSNSClient client; 
SharedPreferences userPreferences; 
ProfileData profileData; 
String token; 

@Override 
protected Void doInBackground(ARScreen.Container... containers) { 
    ARScreen.Container container = containers[0]; 
    profileData = container.profileData; 
    userPreferences = container.userPreferences; 
    token = container.token; 
    BasicAWSCredentials credentials = new BasicAWSCredentials(profileData.getSubscribeId(), profileData.getSubscribeSecret()); 
    client = new AmazonSNSClient(credentials); 
    client.setRegion(Region.getRegion(Regions.AP_SOUTHEAST_1)); 
    registerWithSNS(token); 
    return null; 
} 

@SuppressLint("CommitPrefEdits") 
@SuppressWarnings({"deprecation", "unchecked"}) 
public void registerWithSNS(String regId) { 

    String endpointArn = retrieveEndpointArn(); 

    boolean updateNeeded = false; 
    boolean createNeeded = (null == endpointArn); 

    if (createNeeded) { 
     // No platform endpoint ARN is stored; need to call createEndpoint. 
     endpointArn = createEndpoint(regId); 
     createNeeded = false; 
    } 

    System.out.println("Retrieving platform endpoint data..."); 
    // Look up the platform endpoint and make sure the data in it is current, even if 
    // it was just created. 
    try { 
     GetEndpointAttributesRequest geaReq = 
       new GetEndpointAttributesRequest() 
         .withEndpointArn(endpointArn); 
     GetEndpointAttributesResult geaRes = 
       client.getEndpointAttributes(geaReq); 

     updateNeeded = !geaRes.getAttributes().get("Token").equals(regId) 
       || !geaRes.getAttributes().get("Enabled").equalsIgnoreCase("true"); 

    } catch (NotFoundException nfe) { 
     // We had a stored ARN, but the platform endpoint associated with it 
     // disappeared. Recreate it. 
     createNeeded = true; 
    } 

    if (createNeeded) { 
     createEndpoint(regId); 
    } 

    System.out.println("updateNeeded = " + updateNeeded); 

    if (updateNeeded) { 
     // The platform endpoint is out of sync with the current data; 
     // update the token and enable it. 
     System.out.println("Updating platform endpoint " + endpointArn); 
     Map attribs = new HashMap(); 
     attribs.put("Token", regId); 
     attribs.put("Enabled", "true"); 
     SetEndpointAttributesRequest saeReq = 
       new SetEndpointAttributesRequest() 
         .withEndpointArn(endpointArn) 
         .withAttributes(attribs); 
     client.setEndpointAttributes(saeReq); 

    } 

    String subscriptionId = client.subscribe(new SubscribeRequest() 
      .withEndpoint(endpointArn) 
      .withProtocol("application") 
      .withTopicArn(profileData.getSnstopic()) 
    ).getSubscriptionArn(); 

    System.out.println("Id" + subscriptionId); 
    SubscribeRequest subscribeRequest = new SubscribeRequest(profileData.getSnstopic(), "application", endpointArn); 
    SubscribeResult result = client.subscribe(subscribeRequest); 

    if (result != null) { 
     SharedPreferences.Editor editor = userPreferences.edit(); 
     editor.putBoolean("isSubscribed", true); 
     editor.commit(); 
    } 
} 

/** 
* @return never null 
*/ 
private String createEndpoint(String token) { 

    String endpointArn; 
    try { 
     System.out.println("Creating platform endpoint with token " + token); 
     CreatePlatformEndpointRequest cpeReq = 
       new CreatePlatformEndpointRequest() 
         .withPlatformApplicationArn("My Platform Application ARN") 
         .withToken(token); 
     CreatePlatformEndpointResult cpeRes = client 
       .createPlatformEndpoint(cpeReq); 
     endpointArn = cpeRes.getEndpointArn(); 
    } catch (InvalidParameterException ipe) { 
     String message = ipe.getErrorMessage(); 
     System.out.println("Exception message: " + message); 
     Pattern p = Pattern 
       .compile(".*Endpoint (arn:aws:sns[^ ]+) already exists " + 
         "with the same token.*"); 
     Matcher m = p.matcher(message); 
     if (m.matches()) { 
      // The platform endpoint already exists for this token, but with 
      // additional custom data that 
      // createEndpoint doesn't want to overwrite. Just use the 
      // existing platform endpoint. 
      endpointArn = m.group(1); 
     } else { 
      // Rethrow the exception, the input is actually bad. 
      throw ipe; 
     } 
    } 
    storeEndpointArn(endpointArn); 
    return endpointArn; 
} 

/** 
* @return the ARN the app was registered under previously, or null if no 
* platform endpoint ARN is stored. 
*/ 
private String retrieveEndpointArn() { 
    // Retrieve the platform endpoint ARN from permanent storage, 
    // or return null if null is stored. 
    return userPreferences.getString("endPointArn", null); 
} 


/** 
* Stores the platform endpoint ARN in permanent storage for lookup next time. 
*/ 
@SuppressLint("CommitPrefEdits") 
private void storeEndpointArn(String endpointArn) { 
    // Write the platform endpoint ARN to permanent storage. 
    SharedPreferences.Editor editor = userPreferences.edit(); 
    editor.putString("endPointArn", endpointArn); 
    editor.commit(); 
} 

내가 로그 console.The 문제에서 서브 스크립 션 ID를 볼 수 있습니다. 코드에서 뭔가 빠졌습니까? 어떤 도움을 주시면 감사하겠습니다 !!

+0

플랫폼 응용 프로그램 ARN을 만드는 동안 자격 증명으로 API 키를 추가 했습니까 ??? –

답변

0

모든 구성을 올바르게 설정 한 경우 (예 : 푸시 및 Cognito가있는 SNS와 같은 AWS의 서비스를 연결하는 데 MobileHub를 사용하는 것이 좋습니다) 앱에 구현 한 PushListenerService 만주의하면됩니다.

첫째로, 당신은 당신의 AndroidManifest.xml에 다음 라인을 추가했는지 확인합니다

:

<!-- 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.yourpackagename" /> 
     </intent-filter> 
    </receiver> 

    <service 
     android:name=".push.service.PushListenerService" 
     android:exported="false"> 
     <intent-filter> 
      <action android:name="com.google.android.c2dm.intent.RECEIVE" /> 
     </intent-filter> 
    </service> 

    <!-- END - PUSH NOTIFICATIONS WITH GOOGLE CLOUD MESSAGING (GCM) --> 

또한을, 당신의 PushListenerService, 당신은 중포 기지와 아마존 MobileHub 콘솔에서 보낸 메시지를 얻을 수 있는지 확인

/** 
* 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. 
    String result = data.containsKey("default") ? data.getString("default") : data.getString(
      "message", ""); 
    if(result.isEmpty()){ 
     result = data.getBundle("notification").get("body").toString(); 
    } 

    return result; 
} 
관련 문제