【发布时间】:2016-05-20 16:36:17
【问题描述】:
您好,我有一个设置活动,其中有一个名为“显示预览”的复选框。我想做的事情是,如果选中此复选框,那么它会向广播接收器发送一些内容。在广播接收器中,我想获取复选框值,如果它是真的,即复选框被选中,那么它会在收到新短信时在通知栏中显示通知。如果未选中复选框的值,则不会显示通知。现在我可以通过共享首选项存储复选框的值,但我没有在我的接收器类中获得该值。
这是我在设置活动中的代码:`
CheckBox ch1;
private SharedPreferences loginPreferences;
private SharedPreferences.Editor loginPrefsEditor;
private Boolean saveLogin;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.settings);
ch1 = (CheckBox) findViewById(R.id.checkBox1);
loginPreferences = getSharedPreferences("loginPrefs", MODE_PRIVATE);
loginPrefsEditor = loginPreferences.edit();
saveLogin = loginPreferences.getBoolean("saveLogin", false);
if (saveLogin == true) {
ch1.setChecked(true);
}
}
@Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
if (ch1.isChecked())
{
loginPrefsEditor.putBoolean("saveLogin", true);
loginPrefsEditor.commit();
Intent intent = new Intent("my.action.string");
intent.putExtra("checked", "1");
sendBroadcast(intent);
}
else {
loginPrefsEditor.clear();
loginPrefsEditor.commit();
}
如您所见,我编写了一个代码,当使用时停止该活动,如果检查了该值,则该值应该转到接收器类。 现在在接收器类中是我的代码:
String action = intent.getAction();
String state = "";
if(action.equals("my.action.string")){
state = intent.getExtras().getString("checked");
}
最后我正在检查如果 state 的值为 1 则应该显示通知。 这是通知的代码
if (state == "1" )
{
NotificationCompat.Builder notify = new NotificationCompat.Builder(context);
notify.setSmallIcon(R.drawable.newnotifysmall);
notify.setContentTitle(title);
notify.setContentText(msgBody);
notify.setAutoCancel(true);
Notification notification = new Notification();
notification.defaults |= Notification.DEFAULT_VIBRATE;
//notify.setVibrate(new long[]{1000, 1000, 1000, 1000, 1000});
notify.setLights(Color.GREEN, 2000, 2000);
notify.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
Intent notificationIntent = new Intent(Intent.ACTION_MAIN);
notificationIntent.addCategory(Intent.CATEGORY_DEFAULT);
notificationIntent.setType("vnd.android-dir/mms-sms");
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent intentt = PendingIntent.getActivity(context, 0,notificationIntent, 0);
notify.setContentIntent(intentt);
NotificationManager notificationManager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notify.build());
}
我也在接收器的清单文件中写了这个:
<action android:name="my.action.string"></action>
但我认为该值没有传递 tor 接收器类。请帮忙
【问题讨论】:
-
比较???我不是在比较我只是没有从活动到接收者的价值。我是否需要在接收器中获取偏好值?
-
state == "1"不是你比较Strings 的方式。 -
比较是下一步,先生。我会自己处理,但第一个问题是我没有收到接收器中的值
-
您说“我认为该值未通过 Tor 接收器类”。你确定吗?您是否已调试并检查过 Receiver 中的 extra 值?
标签: android checkbox broadcastreceiver sharedpreferences