所以我想用SharedPreference用我的偏好,但我同時使用此代碼有一個問題:getBaseContext無法使用,可以替換它嗎?
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(Context);
我不能使用getBaseContext();方法,因爲我的類沒有擴展Activity類。我該怎麼辦?我試圖使用onReceive給出的上下文(arg0),但它仍然不起作用。
這是我的代碼:
public class SMSReceiver extends BroadcastReceiver{
private static final int NOTIF_ID = 0;
@Override
public void onReceive(Context arg0, Intent arg1) {
// TODO Auto-generated method stub
Bundle bundle = arg1.getExtras();
SmsMessage[] msgs = null;
String str = "";
if (bundle != null) {
Object[] pdus = (Object[]) bundle.get("pdus");
msgs = new SmsMessage[pdus.length];
for (int i = 0; i < msgs.length; i++) {
msgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
str += "You Get New SMS from "
+ msgs[i].getOriginatingAddress();
str += " :";
str += msgs[i].getMessageBody().toString();
str += "\n";
Toast.makeText(arg0, str, Toast.LENGTH_SHORT).show();
**//THIS IS THE SHAREDPREFERENCES**
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(**NEED HELP HERE**);
boolean notifStatus = sp.getBoolean("notification", true);
if (notifStatus) {
NotificationManager nm = (NotificationManager) arg0
.getSystemService(Context.NOTIFICATION_SERVICE);
String tickerText = str;
Notification notif = new Notification(
R.drawable.ic_launcher, tickerText,
System.currentTimeMillis());
notif.flags = Notification.FLAG_AUTO_CANCEL;
String contentTitle = msgs[i].getOriginatingAddress();
String contentText = msgs[i].getMessageBody().toString();
Intent intent = new Intent(arg0, SMSReply.class);
PendingIntent pi = PendingIntent.getActivity(arg0, 0,
intent, 0);
notif.setLatestEventInfo(arg0, contentTitle, contentText,
pi);
notif.defaults = Notification.DEFAULT_ALL;
nm.notify(NOTIF_ID, notif);
String tempSMS = msgs[i].getOriginatingAddress();
Intent pass = new Intent();
Bundle bundlePass = new Bundle();
bundlePass.putString("key", tempSMS);
pass.putExtras(bundlePass);
}
}
}
}
的想法是我想用一首
也許你可以使用arg0.getApplicationContext – nandeesh 2012-03-04 16:35:01