我已经创建了一个从PushBots接收推送通知的应用程序。
我正在成功地接收推送通知,但我希望将推送数据存储在SharedPreferences中,并将其显示为另一个包含RecyclerView的活动。
我知道内容提供商是一种更好的方法,但我现在想坚持使用SharedPreferences。
这是我定制的广播接收器
public class customHandler extends BroadcastReceiver
{
private static final String TAG = "customHandler";
@Override
public void onReceive(Context context, Intent intent)
{
String action = intent.getAction();
Log.d(TAG, "action=" + action);
// Handle Push Message when opened
if (action.equals(PBConstants.EVENT_MSG_OPEN)) {
//Check for Pushbots Instance
Pushbots pushInstance = Pushbots.sharedInstance();
if(!pushInstance.isInitialized()){
Log.d("Initializing Pushbots.");
Pushbots.sharedInstance().init(context.getApplicationContext());
}
//Clear Notification array
if(PBNotificationIntent.notificationsArray != null){
PBNotificationIntent.notificationsArray = null;
}
HashMap<?, ?> PushdataOpen = (HashMap<?, ?>) intent.getExtras().get(PBConstants.EVENT_MSG_OPEN);
Log.w(TAG, "User clicked notification with Message: " + PushdataOpen.get("message"));
//Report Opened Push Notification to Pushbots
if(Pushbots.sharedInstance().isAnalyticsEnabled()){
Pushbots.sharedInstance().reportPushOpened( (String) PushdataOpen.get("PUSHANALYTICS"));
}
//Start Main Activity On CLicking Notification
String packageName = context.getPackageName();
Intent resultIntent = new Intent(context.getPackageManager().getLaunchIntentForPackage(packageName));
resultIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK| Intent.FLAG_ACTIVITY_CLEAR_TASK);
resultIntent.putExtras(intent.getBundleExtra("pushData"));
Pushbots.sharedInstance().startActivity(resultIntent);
// Handle Push Message when received
}else if(action.equals(PBConstants.EVENT_MSG_RECEIVE)){
HashMap<?, ?> PushdataOpen = (HashMap<?, ?>) intent.getExtras().get(PBConstants.EVENT_MSG_RECEIVE);
Log.w(TAG, "User Received notification with Message: " + PushdataOpen.get("message"));
}
}
}发布于 2016-04-15 03:39:06
创建一个自定义的PushData类,并使用Gson库将数据保存为字符串。
这里是一个干净的示例
发布于 2016-04-15 04:00:22
试试看。
public void addNotification(String notification) {
// get old notifications
String oldNotifications = getNotifications();
if (oldNotifications != null) {
oldNotifications += "|" + notification;
} else {
oldNotifications = notification;
}
editor.putString(KEY_NOTIFICATIONS, oldNotifications);
editor.commit();
}
public String getNotifications() {
return pref.getString(KEY_NOTIFICATIONS, null);
}然后得到它
String oldNotification = AppController.getInstance().getPrefManager().getNotifications();
List<String> messages = Arrays.asList(oldNotification.split("\\|"));发布于 2016-04-15 04:01:12
用于在SharedPreferences中放置字符串:
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString(key, value);
editor.commit();用于获取片段中的共享首选项:
SharedPreferences prefs = getActivity().getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
String name = prefs.getString(key, "default value");https://stackoverflow.com/questions/36637744
复制相似问题