简体   繁体   中英

Onesignal Push notifications is delivered But not receaved by any device

Hello i am using onesignal push notifications in my android. I am trying to send some push notifications for test the message but after sending push notifications i cannot get any notifications but onsignal show's that message is delivered.

Here is build.gradle

I am using Onesignal jar sdk because i didn't have pc so i cannot use Studio i am using Aide Ide to build my app.

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>

I am using meta-data for onsignal app id and project number afterthat onsignal recognise my app.

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


    }

Anyone find any error in this code ? Why i cannot get any notifications even onesignal delivered the notifications to my app?

I am sure that you forget some permissions that onesignal need to receive notifications. Try this 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);
            }
        }
    }

}

I am very sure now you receive notifications.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM