如何在安卓设备上读取One Signal推送通知消息?

7
我需要读取OneSignal的推送通知信息。根据这些信息,我需要在我的电商应用程序中更改产品的交付状态。
如何读取?

你正在使用GCM推送通知,还是使用了第三方工具? - Jeevanandhan
One Signal 是一个第三方通知服务。 - Parama Sudha
你处理过这个吗? - Daryn
6个回答

1
添加
compile 'com.onesignal:OneSignal:[3.7.1, 3.99.99]'

在 Android 下面添加这段代码。
manifestPlaceholders = [onesignal_app_id: "app_id Enter here",
                         onesignal_google_project_number: "REMOTE"]

1
class ExampleNotificationReceivedHandler implements OneSignal.NotificationReceivedHandler {
    @Override
    public void notificationReceived(OSNotification notification) {

       try {
        String type = data.optString("type","");
        if (type.equals("your_silent_type")) { // your condition
            notification.displayType = OSNotification.DisplayType.None;
            notification.isAppInFocus = false;

            // if notification already shown then just remove it, from notification tray
            String ns = Context.NOTIFICATION_SERVICE;
            NotificationManager nMgr = (NotificationManager) getSystemService(ns);
            nMgr.cancel(notification.androidNotificationId);

        }
       } catch(Exception e){} 
    }
}

1
以下是OneSignal关于如何在接收到通知时运行自定义代码的指南:
  1. 开启content-available(iOS)或silent-notification(Android)字段。这将导致您的应用程序在接收到通知时自动在后台唤醒(即使未点击)。您的自定义代码必须使用本地代码编写,在Android上使用Java,在iOS上使用Swift或Objective-C。有关接收和处理事件的详细信息,请参见苹果的content-available for iOS和我们的Android Background Data指南。
  2. 在您的应用程序中,我们提供了一个API,您可以在发生以上情况时使用它来运行自定义代码。然后,您的自定义代码可以将通知内容的副本保存在设备上,以便在下次启动应用程序时在活动订阅中显示。或者它可以将其副本保存在您的服务器上。
通知可以包含元数据(在OneSignal API中提供为“data”),将传递给您的自定义代码。

0

你需要扩展NotificationsReceiveHandler并将其设置为你的OneSignal实例。

在这个例子中,我正在捕获通知并检查NotificationsType。

NotificationsType是我在服务器后端创建的一个对象,以便更好地了解客户端中通知角色的情况。

public class CustomNotificationReceivedHandler implements OneSignal.NotificationReceivedHandler {

@Override
public void notificationReceived(OSNotification notification) {

    try {
        NotificationsType type = NotificationsType.fromValue(notification.payload.additionalData.optInt("type"));
        if (type.getValue() == NotificationsType.NEW_MESSAGE.getValue()) {
            notification.displayType = OSNotification.DisplayType.None;

            final Message message = new Gson().fromJson(notification.payload.additionalData.getString("payload"), Message.class);

            EventBus.getDefault().post(new NewMessageReceived(message));
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
}

0
如何在Android清单文件中使用元数据调用

目前你的回答不够清晰,请编辑并添加更多细节,以帮助其他人理解它如何回答问题。你可以在帮助中心找到有关如何编写好答案的更多信息。 - Community
如果您有新的问题,请通过单击提问按钮来提出。如果它有助于提供上下文,请包含此问题的链接。- 来自审核 - Hooman

0

这很简单

首先,您可以从OneSignal.db中读取所有通知,它是您应用程序中的本地数据库

现在,如何从OneSignal.db中读取 只需使用下面的类即可

public class DataBaseHelper extends SQLiteOpenHelper {

    private Context mycontext;
    private static String DB_NAME = "OneSignal.db";
    private static String DB_PATH = "/data/data/" + BuildConfig.APPLICATION_ID + "/databases/";
    public SQLiteDatabase myDataBase;

    public DataBaseHelper(Context context) throws IOException {
        super(context, DB_NAME, null, 8);
        this.mycontext = context;
        boolean dbexist = checkdatabase();
        if (dbexist) {
            System.out.println("Database exists");
            opendatabase();
        } else {
            System.out.println("Database doesn't exist");
            createdatabase();
        }
    }

    public  void addmessgetodatabse(String message)
    {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("feild2", message);

        db.insert("data", null, values);
    }
    public void createdatabase() throws IOException {
        boolean dbexist = checkdatabase();
        if (dbexist) {
            System.out.println(" Database exists.");
        } else {
            this.getReadableDatabase();
            this.close();
            try {
                copydatabase();
            } catch (IOException e) {
                throw new Error("Error copying database");
            }
        }
    }

    private boolean checkdatabase() {

        boolean checkdb = false;
        try {
            String myPath = DB_PATH + DB_NAME;
            File dbfile = new File(myPath);
            checkdb = dbfile.exists();
        } catch (SQLiteException e) {
            System.out.println("Database doesn't exist");
        }
        return checkdb;
    }

    private void copydatabase() throws IOException {
        //Open your local db as the input stream
        InputStream myinput = mycontext.getAssets().open(DB_NAME);

        // Path to the just created empty db
        String outfilename = DB_PATH + DB_NAME;

        //Open the empty db as the output stream
        OutputStream myoutput = new FileOutputStream(outfilename);

        // transfer byte to inputfile to outputfile
        byte[] buffer = new byte[1024];
        int length;
        while ((length = myinput.read(buffer)) > 0) {
            myoutput.write(buffer, 0, length);
        }

        //Close the streams
        myoutput.flush();
        myoutput.close();
        myinput.close();
    }
    public void opendatabase() throws SQLException {
        //Open the database
        String mypath = DB_PATH + DB_NAME;
        myDataBase = SQLiteDatabase.openDatabase(mypath, null, SQLiteDatabase.OPEN_READWRITE);
    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {
        sqLiteDatabase.execSQL(MyGolas.CREATE_TABLE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
        if(i1==2)
        {
            sqLiteDatabase.execSQL(MyGolas.CREATE_TABLE);
        }
    }

    public void deleteNote(MyGolas note) {
        SQLiteDatabase db = this.getWritableDatabase();
        db.delete(MyGolas.TABLE_NAME, MyGolas.COLUMN_ID + " = ?",
                new String[]{String.valueOf(note.getId())});
        db.close();
    }
    public List<MyGolas> getAllGOLES() {
        List<MyGolas> notes = new ArrayList<>();

        // Select All Query
        String selectQuery = "SELECT  * FROM " + MyGolas.TABLE_NAME + " ORDER BY " +
                MyGolas.COLUMN_TIMESTAMP + " DESC";

        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);

        // looping through all rows and adding to list
        if (cursor.moveToFirst()) {
            do {
                MyGolas note = new MyGolas();
                note.setId(cursor.getInt(cursor.getColumnIndex(MyGolas.COLUMN_ID)));
                note.setTitle(cursor.getString(cursor.getColumnIndex(MyGolas.COLUMN_title)));
                note.setNote(cursor.getString(cursor.getColumnIndex(MyGolas.COLUMN_NOTE)));
                note.setTimestamp(cursor.getString(cursor.getColumnIndex(MyGolas.COLUMN_TIMESTAMP)));

                notes.add(note);
            } while (cursor.moveToNext());
        }

        db.close();

        return notes;
    }
    public ArrayList<String> getmessage() {
        ArrayList<String> contactList = new ArrayList<String>();
        String selectQuery;
            selectQuery = "SELECT * FROM notification"  ;
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);
        if (cursor.moveToFirst()) {
            do {
                contactList.add(cursor.getString(9));
            } while (cursor.moveToNext());
        }
        return contactList;
    }

    public String getgolas() {
        String result ="";
        String selectQuery;
        selectQuery = "SELECT  title FROM mygolse"  ;
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);
        if (cursor.moveToFirst()) {
            do {
             result = cursor.getString(0);
            } while (cursor.moveToNext());
        }
        return result;
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接