提供Onesignal推送通知但未被任何设备接收

时间:2017-11-09 13:44:50

标签: android push-notification onesignal

您好我在我的机器人中使用信号推送通知。 我正在尝试发送一些推送通知来测试邮件,但是在发送推送通知后,我无法收到任何通知,但是在信号显示该邮件已发送。

这是build.gradle

我正在使用Onesignal jar sdk因为我没有电脑,所以我无法使用Studio我正在使用Aide Ide构建我的应用。

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>

我正在使用meta-data onsignal app id和项目编号,然后onsignal识别我的应用。

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


    }

有人在此代码中发现任何错误吗? 为什么我无法收到任何通知,即使是那些信号也会将通知发送到我的应用程序?

1 个答案:

答案 0 :(得分:0)

我确信您忘记了信号需要接收通知的一些权限。 试试这个 的AndroidManifest.xml

SELECT
    MatCard.Name as name
  , MatCard.Price24 as wholesale_price  -- just include the column here
  , MatCard.Price4 as retail_price
  , Barcode.Barcode as code 
FROM Barcode
INNER JOIN MatCard ON MatCard.Num = Barcode.Num 
WHERE Barcode.Barcode = :code

YourApplication.java

<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>

我非常确定您现在收到通知。