getBaseContext无法使用,可以替换它吗?

时间:2012-03-04 15:47:06

标签: android notifications android-context

所以我想使用SharedPreference来使用我的偏好,但是在使用这段代码时我遇到了一个问题:

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

我的想法是想要使用首选项打开/关闭我的通知

2 个答案:

答案 0 :(得分:2)

你可以这样做:

SharedPreferences sp = arg0.getSharedPreferences(yourPreferencesName, arg0.MODE_PRIVATE);

答案 1 :(得分:0)

答案: 对不起,我犯了一个语法错误,所以基本上我们可以这样做:

SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(arg0);

boolean notifStatus = sp.getBoolean(“notification”,true);

这是有效的,谢谢:D