2017-11-09 6 views
1

こんにちは、私はアンドロイドでone信号プッシュ通知を使用しています。 私はいくつかのプッシュ通知を送信しようとしていますが、プッシュ通知を送信した後は通知を受け取ることはできませんが、そのメッセージは配信されています。私は私のアプリを構築するために補佐官IDEを使用していStudioを使用することはできませんので、私はPCを持っていなかったので、私はOnesignal jar sdkを使用しています Onesignalプッシュ通知が配信されますが、いずれのデバイスでも受信されません。

build.gradleここ

です。

android { 
    compileSdkVersion 26 
    buildToolsVersion '26.0.1' 

    defaultConfig { 
     applicationId "com.mytest.test" 

     // TODO: Please update the OneSignal ID below to yours! 

     minSdkVersion 15 
     targetSdkVersion 26 
     versionCode 1 
     versionName "1.0" 
     manifestPlaceholders = [onesignal_app_id: "", 
           // Project number pulled from dashboard, local value is ignored. 
           onesignal_google_project_number: "REMOTE"] 

    } 
    buildTypes { 
     release { 
      minifyEnabled false 
      proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 
     } 
    } 
} 

dependencies { 


    compile fileTree(dir: 'libs', include: ['*.jar']) 

    // OneSignal requires at least version 7.0.0 of GMS but the newest version is recommend. 
    // Required for OneSignal, even if you have added FCM. 
    compile 'com.google.android.gms:play-services-gcm:8.1.0' 
    compile 'com.android.support:palette-v7:23.1.1' 
    // Required for geotagging 
    compile 'com.google.android.gms:play-services-location:8.1.0' 

    // play-services-analytics is only needed when using 8.1.0 or older. 
    compile 'com.google.android.gms:play-services-analytics:8.1.0' 
    //noinspection GradleCompatible 

    compile 'com.android.support.constraint:constraint-layout:1.0.2' 

compile files('libs/OneSignalSDK.jar') 
} 

MyApplication.java

public class MyApplication extends Application { 

    @Override public void onCreate() {  super.onCreate(); 

     OneSignal.startInit(this)   .setNotificationOpenedHandler(new ExampleNotificationOpenedHandler())   .init(); } 
      // Fires when a notificaiton is opened by tapping on it or one is received while the app is runnning. private class ExampleNotificationOpenedHandler implements OneSignal.NotificationOpenedHandler {   // This fires when a notification is opened by tapping on it.  @Override  public void notificationOpened(OSNotificationOpenResult result) {   OSNotificationAction.ActionType actionType = result.action.type;   OneSignal.setInFocusDisplaying(OneSignal.OSInFocusDisplayOption.Notification); 

      JSONObject data = result.notification.payload.additionalData;   String launchUrl = result.notification.payload.launchURL; // update docs launchUrl 

      String customKey;   String openURL = null;   Object activityToLaunch = MainActivity.class; 

      if (data != null) { 
       customKey = data.optString("customkey", null); 
       openURL = data.optString("openURL", null); 

       if (customKey != null) 
        Log.i("hitpush", "customkey set with value: " + customKey); 

       if (openURL != null) 
        Log.i("hitpush", "openURL to webview with URL value: " + openURL);   } 

      if (actionType == OSNotificationAction.ActionType.ActionTaken) { 
       Log.i("hitpush", "Button pressed with id: " + result.action.actionID); 
       if (result.action.actionID.equals("id1")) { 
        Log.i("hitpush", "button id called: " + result.action.actionID); 
        activityToLaunch = MainActivity.class; 
       } else { 
        Log.i("hitpush", "button id called: " + result.action.actionID); 
       } 

      }   // The following can be used to open an Activity of your choice.   // Replace - getApplicationContext() - with any Android Context.   // Intent intent = new Intent(getApplicationContext(), YourActivity.class);    Intent intent = new Intent(getApplicationContext(), (Class<?>) activityToLaunch);   // intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);   intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);    intent.putExtra("openURL", openURL);   Log.i("hitpush", "openURL = " + openURL);   // startActivity(intent);   startActivity(intent); 

      // Add the following to your AndroidManifest.xml to prevent the launching of your main Activity    // if you are calling startActivity above.   /* 
      <application ...> 
      <meta-data android:name="com.onesignal.NotificationOpened.DEFAULT" android:value="DISABLE" /> 
      </application> 
      */ 

     } } 

のAndroidManifest.xml

<uses-permission android:name="android.permission.INTERNET" /> 

    <!-- All OneSignal manifest entries are added for you automatically from the OneSignal aar gradle entry. --> 


    <!-- Optional permission, needed for geo tagging feature. --> 
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> 

    <application 
     android:name=".MyApplication" 
     android:icon="@drawable/ic_launcher" 
     android:label="@string/app_name" 
     android:theme="@style/AppTheme"> 


     <!-- Disbale opening of launcher Activity --> 
     <meta-data android:name="com.onesignal.NotificationOpened.DEFAULT" android:value="DISABLE" /> 


     <service 
      android:name=".MyNotificationExtenderService" 
      android:exported="false"> 
      <intent-filter> 
       <action android:name="com.onesignal.NotificationExtender" /> 
      </intent-filter> 
     </service> 
     <!-- Disable Badges --> 
     <!-- <meta-data android:name="com.onesignal.BadgeCount" android:value="DISABLE" /> --> 

     <activity android:name=".MainActivity"> 
      <intent-filter> 
       <action android:name="android.intent.action.MAIN" /> 

       <category android:name="android.intent.category.LAUNCHER" /> 
      </intent-filter> 
     </activity> 


     <meta-data 
      android:name="com.google.android.gms.version" 
      android:value="@integer/google_play_services_version" /> 
     <meta-data 
      android:name="onesignal_app_id" 
      android:value="" /> 
     <meta-data 
      android:name="onesignal_google_project_number" 
      android:value="" /> 

    </application> 

私は私のアプリを認識onsignal afterthat onsignalアプリIDとプロジェクト番号にmeta-dataを使用しています。

MainActivity.java

private static Activity currentActivity; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     final TextView textView = (TextView)findViewById(R.id.debug_view); 
     textView.setText("OneSignal is Ready!"); 

     Button onSendTagsButton = (Button)(findViewById(R.id.send_tags_button)); 
     onSendTagsButton.setOnClickListener(new View.OnClickListener() { 
       @Override 
       public void onClick(View view) { 
        JSONObject tags = new JSONObject(); 
        try { 
         tags.put("key1", "value1"); 
         tags.put("user_name", "Jon"); 
        } catch (JSONException e) { 
         e.printStackTrace(); 
        } 
        OneSignal.sendTags(tags); 
        textView.setText("Tags sent!"); 
       } 

      }); 

     Button onGetTagsButton = (Button)(findViewById(R.id.get_tags_button)); 
     onGetTagsButton.setOnClickListener(new View.OnClickListener() { 
       @Override 
       public void onClick(View view) { 
        final Collection<String> receivedTags = new ArrayList<String>(); 
        OneSignal.getTags(new OneSignal.GetTagsHandler() { 
          @Override 
          public void tagsAvailable(final JSONObject tags) { 
           Log.d("debug", tags.toString()); 
           new Handler(Looper.getMainLooper()).post(new Runnable() { 
             @Override 
             public void run() { 
              receivedTags.add(tags.toString()); 
              textView.setText("Tags Received: " + receivedTags); 
             } 
            }); 
          } 
         }); 
       } 
      }); 

     Button onDeleteOrUpdateTagsButton = (Button)(findViewById(R.id.delete_update_tags_button)); 
     onDeleteOrUpdateTagsButton.setOnClickListener(new View.OnClickListener() { 
       @Override 
       public void onClick(View view) { 
        OneSignal.getTags(new OneSignal.GetTagsHandler() { 
          @Override 
          public void tagsAvailable(final JSONObject tags) { 
           Log.d("debug", "Current Tags on User: " + tags.toString()); 
           OneSignal.deleteTag("key1"); 
           OneSignal.sendTag("updated_key", "updated_value"); 
           new Handler(Looper.getMainLooper()).post(new Runnable() { 
             @Override 
             public void run() { 
              textView.setText("Updated Tags: " + tags.toString()); 
             } 
            }); 
          } 
         }); 
       } 
      }); 

     Button onGetIDsAvailableButton = (Button)(findViewById(R.id.get_ids_available_button)); 
     onGetIDsAvailableButton.setOnClickListener(new View.OnClickListener() { 
       @Override 
       public void onClick(View view) { 
        OSPermissionSubscriptionState status = OneSignal.getPermissionSubscriptionState(); 
        boolean isEnabled = status.getPermissionStatus().getEnabled(); 

        boolean isSubscribed = status.getSubscriptionStatus().getSubscribed(); 
        boolean subscriptionSetting = status.getSubscriptionStatus().getUserSubscriptionSetting(); 
        String userID = status.getSubscriptionStatus().getUserId(); 
        String pushToken = status.getSubscriptionStatus().getPushToken(); 

        textView.setText("PlayerID: " + userID + "\nPushToken: " + pushToken); 
       } 
      }); 

     Button onPromptLocationButton = (Button)(findViewById(R.id.prompt_location_button)); 
     onPromptLocationButton.setOnClickListener(new View.OnClickListener(){ 
       @Override 
       public void onClick(View view) { 
        OneSignal.promptLocation(); 
        /* 
        Make sure you have one of the following permissions in your AndroidManifest.xml 
        <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/> 
        <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/> 
        */ 
       } 
      }); 

     Button onSendNotification1 = (Button)(findViewById(R.id.send_notification_button)); 
     onSendNotification1.setOnClickListener(new View.OnClickListener() { 
       @Override 
       public void onClick(View view) { 
        OSPermissionSubscriptionState status = OneSignal.getPermissionSubscriptionState(); 
        String userId = status.getSubscriptionStatus().getUserId(); 
        String pushToken = status.getSubscriptionStatus().getPushToken(); 
        boolean isSubscribed = status.getSubscriptionStatus().getSubscribed(); 

        if (isSubscribed) { 
         textView.setText("Subscription Status, is subscribed:" + isSubscribed); 
         try { 
          JSONObject notificationContent = new JSONObject("{'contents': {'en': 'The notification message or body'}," + 
                      "'include_player_ids': ['" + userId + "'], " + 
                      "'headings': {'en': 'Notification Title'}, " + 
                      "'big_picture': 'http://i.imgur.com/DKw1J2F.gif'}"); 
          OneSignal.postNotification(notificationContent, null); 
         } catch (JSONException e) { 
          e.printStackTrace(); 
         } 
        } 
       } 
      }); 

     Button onSendNotification2 = (Button)(findViewById(R.id.send_notification_button2)); 
     onSendNotification2.setOnClickListener(new View.OnClickListener() { 
       @Override 
       public void onClick(View view) { 
        OSPermissionSubscriptionState status = OneSignal.getPermissionSubscriptionState(); 
        String userID = status.getSubscriptionStatus().getUserId(); 
        String pushToken = status.getSubscriptionStatus().getPushToken(); 
        boolean isSubscribed = status.getSubscriptionStatus().getSubscribed(); 

        if (isSubscribed) { 
         textView.setText("Subscription Status, is subscribed:" + isSubscribed); 
         try { 
          OneSignal.postNotification(new JSONObject("{'contents': {'en':'Tag substitution value for key1 = {{key1}}'}, " + 
                     "'include_player_ids': ['" + userID + "'], " + 
                     "'headings': {'en': 'Tag sub Title HI {{user_name}}'}, " + 
                     "'data': {'openURL': 'https://imgur.com'}," + 
                     "'buttons':[{'id': 'id1', 'text': 'Go to GreenActivity'}, {'id':'id2', 'text': 'Go to MainActivity'}]}"), 
           new OneSignal.PostNotificationResponseHandler() { 
            @Override 
            public void onSuccess(JSONObject response) { 
             Log.i("OneSignalExample", "postNotification Success: " + response.toString()); 
            } 

            @Override 
            public void onFailure(JSONObject response) { 
             Log.e("OneSignalExample", "postNotification Failure: " + response.toString()); 
            } 
           }); 
         } catch (JSONException e) { 
          e.printStackTrace(); 
         } 
        } 
       } 
      }); 

     final Switch onSetSubscriptionSwitch = (Switch)(findViewById(R.id.set_subscription_switch)); 
     onSetSubscriptionSwitch.setOnClickListener(new View.OnClickListener() { 
       @Override 
       public void onClick(View view) { 
        if (onSetSubscriptionSwitch.isChecked()) { 
         OneSignal.setSubscription(true); 
         textView.setText("User CAN receive notifications if turned on in Phone Settings"); 
        } 
        else { 
         OneSignal.setSubscription(false); 
         textView.setText("User CANNOT receive notifications, even if they are turned on in Phone Settings"); 
        } 
       } 
      }); 


    } 

誰もがこのコードでエラーを見つけますか? なぜ私は通知を受け取ることができませんも、私のアプリに通知を配信?

+0

あなたのoneignalアプリIDを削除しますか? – DroiDev

+0

????私はoneignalサーバーから通知を受け取っていませんでした。それは問題です。上記のコードから –

+0

.....あなたのシグナルIDが1つあります...削除してください。この時点で – DroiDev

答えて

0

通知を受け取るために必要な権限を忘れることは確実です。この のAndroidManifest.xml

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> 
    <uses-permission android:name="android.permission.INTERNET" /> 
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> 
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 
    <uses-permission android:name="android.permission.VIBRATE" /> 
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" /> 
    <uses-permission android:name="android.permission.WAKE_LOCK" /> 
    <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" /> 

    <uses-permission android:name="com.mytest.test.permission.C2D_MESSAGE" /> 
    <uses-permission android:name="com.sec.android.provider.badge.permission.READ" /> 
    <uses-permission android:name="com.sec.android.provider.badge.permission.WRITE" /> 
    <uses-permission android:name="com.htc.launcher.permission.READ_SETTINGS" /> 
    <uses-permission android:name="com.htc.launcher.permission.UPDATE_SHORTCUT" /> 
    <uses-permission android:name="com.sonyericsson.home.permission.BROADCAST_BADGE" /> 
    <uses-permission android:name="com.sonymobile.home.permission.PROVIDER_INSERT_BADGE" /> 
    <uses-permission android:name="com.anddoes.launcher.permission.UPDATE_COUNT" /> 
    <uses-permission android:name="com.majeur.launcher.permission.UPDATE_BADGE" /> 
    <uses-permission android:name="com.huawei.android.launcher.permission.CHANGE_BADGE" /> 
    <uses-permission android:name="com.huawei.android.launcher.permission.READ_SETTINGS" /> 
    <uses-permission android:name="com.huawei.android.launcher.permission.WRITE_SETTINGS" /> 
    <uses-permission android:name="android.permission.READ_APP_BADGE" /> 
    <uses-permission android:name="com.oppo.launcher.permission.READ_SETTINGS" /> 
    <uses-permission android:name="com.oppo.launcher.permission.WRITE_SETTINGS" /> 
    <uses-permission android:name="me.everything.badger.permission.BADGE_COUNT_READ" /> 
    <uses-permission android:name="me.everything.badger.permission.BADGE_COUNT_WRITE" /> 


    <receiver android:name="com.onesignal.GcmBroadcastReceiver" android:permission="com.google.android.c2dm.permission.SEND"> 
     <intent-filter android:priority="999"> 
      <action android:name="com.google.android.c2dm.intent.RECEIVE" /> 
      <category android:name="com.mytest.test" /> 
     </intent-filter> 
    </receiver> 
    <receiver android:name="com.onesignal.NotificationOpenedReceiver" /> 
    <service android:name="com.onesignal.GcmIntentService" /> 
    <service android:name="com.onesignal.GcmIntentJobService" android:permission="android.permission.BIND_JOB_SERVICE" /> 
    <service android:name="com.onesignal.SyncService" /> 
    <activity android:theme="@*android:style/Theme.Translucent.NoTitleBar" android:name="com.onesignal.PermissionsActivity" /> 
    <service android:name="com.onesignal.NotificationRestoreService" /> 
    <service android:name="com.onesignal.NotificationRestoreJobService" android:permission="android.permission.BIND_JOB_SERVICE" /> 
    <receiver android:name="com.onesignal.BootUpReceiver"> 
     <intent-filter> 
      <action android:name="android.intent.action.BOOT_COMPLETED" /> 
      <action android:name="android.intent.action.QUICKBOOT_POWERON" /> 
     </intent-filter> 
    </receiver> 
    <receiver android:name="com.onesignal.UpgradeReceiver"> 
     <intent-filter> 
      <action android:name="android.intent.action.MY_PACKAGE_REPLACED" /> 
     </intent-filter> 
    </receiver> 

YourApplication.java

public class YourApplication extends Application 
{ 
    public void onCreate() { 
     super.onCreate(); 
     OneSignal.setLogLevel(LOG_LEVEL.DEBUG, LOG_LEVEL.WARN); 
     OneSignal.startInit(this).setNotificationOpenedHandler(new ExampleNotificationOpenedHandler()).autoPromptLocation(true).init(); 
    } 


    private class ExampleNotificationOpenedHandler implements NotificationOpenedHandler { 
     private ExampleNotificationOpenedHandler() { 
     } 

     public void notificationOpened(OSNotificationOpenResult result) { 
      ActionType actionType = result.action.type; 
      JSONObject data = result.notification.payload.additionalData; 
      if (data != null) { 
       String customKey = data.optString("customkey", null); 
       if (customKey != null) { 
        Log.i("OneSignalExample", "customkey set with value: " + customKey); 
       } 
      } 
      if (actionType == ActionType.ActionTaken) { 
       Log.i("OneSignalExample", "Button pressed with id: " + result.action.actionID); 
      } 
     } 
    } 

} 

をお試しください 私は今あなたが通知を受け取る非常に確信しています。

+1

Thankxは今働いています:) –

関連する問題