在MainActivity和BroadcastReceiver之间使用SharedPreferences

时间:2014-02-20 14:22:05

标签: android

我想做一个d天的小部件。在MainActivity中,我使用了像这样的SharedPreferences

public class MainActivity extends Activity {
    int startDay;
    int startMonth;
    int startYear;
    int id = 1128;
    long days;
    long diff;
    int countNumber;
    boolean notifyClicked;
    EditText txtview;
    TextView dayCount;
    String message;
    DatePicker datePicker;
    PendingIntent resultPendingIntent;
    Context context;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        context = this;
        txtview = (EditText) findViewById(R.id.txtfield);
        dayCount = (TextView) findViewById(R.id.days);
        datePicker = (DatePicker) findViewById(R.id.datePicker);
        Button startBtn = (Button) findViewById(R.id.btn1);

        // SharedPreferences Load
        SharedPreferences pref = getSharedPreferences("SaveState", 0);
        startDay = pref.getInt("startDay", 0);
        startMonth = pref.getInt("startMonth", 0);
        startYear = pref.getInt("startYear", 0);
        message = pref.getString("message", "");
        countNumber = pref.getInt("countNumber", 0);
        txtview.setText(message);

        startBtn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                startDay = datePicker.getDayOfMonth();
                startMonth = datePicker.getMonth() + 1;
                startYear = datePicker.getYear();
                message = txtview.getText().toString();

                // SharedPreferences Save
                SharedPreferences pref = getSharedPreferences("SaveState", 0);
                SharedPreferences.Editor edit = pref.edit();
                edit.putInt("startDay", startDay);
                edit.putInt("startMonth", startMonth);
                edit.putInt("startYear", startYear);
                edit.putString("message", message);
                edit.putInt("countNumber", countNumber);
                edit.commit();

                Calendar thatDay = Calendar.getInstance();
                thatDay.set(Calendar.DAY_OF_MONTH, startDay);
                thatDay.set(Calendar.MONTH, startMonth - 1); // 0-11 so 1 less
                thatDay.set(Calendar.YEAR, startYear);

                Calendar today = Calendar.getInstance();

                diff = today.getTimeInMillis() - thatDay.getTimeInMillis();
                days = diff / (24 * 60 * 60 * 1000);
                countNumber = (int) days;

                Toast.makeText(getApplicationContext(),
                        countNumber + "일 지났습니다. 알림 버튼을 눌러주세요.",
                        Toast.LENGTH_SHORT).show();

            }
        });

        Intent resultIntent = new Intent(this, ExampleActivity.class);
        resultPendingIntent = PendingIntent.getActivity(this, 0, resultIntent,
                0);

        Button setBtn = (Button) findViewById(R.id.btn2);
        setBtn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                long firstTime = SystemClock.elapsedRealtime();
                firstTime += 10 * 1000;

                AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
                am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
                        firstTime, 10 * 1000, resultPendingIntent);
            }

        });
    }

并做了一个新的IntentActivity扩展BroadcastReceiver,它发出通知

 public class ExampleActivity extends BroadcastReceiver {
            int startDay;
             int startMonth;
             int startYear;
             int id = 1128;
             String message;
             int countNumber;
             NotificationCompat.Builder mBuilder;
             NotificationManager mNotificationManager;
                    @Override
                    public void onReceive(Context arg0, Intent arg1) {
                        // TODO Auto-generated method stub
                        PendingIntent contentIntent = PendingIntent.getActivity(arg0, 0,
                                new Intent(arg0, MainActivity.class), 0);

                        SharedPreferences pref = arg0.getSharedPreferences("SaveState",
                                Context.MODE_PRIVATE);
                        startDay = pref.getInt("startDay", 0);
                        startMonth = pref.getInt("startMonth", 0);
                        startYear = pref.getInt("startYear", 0);
                        countNumber = pref.getInt("countNumber", 0);
                        message = pref.getString("message", "");
                        mBuilder = new NotificationCompat.Builder(arg0)
        .setSmallIcon(R.drawable.heart)
                                .setContentText(countNumber + "")
        .setContentTitle(message + "")
        .setContentIntent(contentIntent);
            mBuilder.setOngoing(true);
            mNotificationManager = (NotificationManager) arg0
    .getSystemService(Context.NOTIFICATION_SERVICE);
            mNotificationManager.notify(id, mBuilder.build());
                    }
                }

但是当我想要这个ExampleActivity时它会强制关闭。编译时没有错误。 这是一个错误日志。

02-20 22:47:21.137: E/AndroidRuntime(4985): FATAL EXCEPTION: main
02-20 22:47:21.137: E/AndroidRuntime(4985): Process: com.example.calculateday, PID: 4985
02-20 22:47:21.137: E/AndroidRuntime(4985): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.calculateday/com.example.calculateday.ExampleActivity}: java.lang.ClassCastException: com.example.calculateday.ExampleActivity cannot be cast to android.app.Activity
02-20 22:47:21.137: E/AndroidRuntime(4985):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2124)
02-20 22:47:21.137: E/AndroidRuntime(4985):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2248)
02-20 22:47:21.137: E/AndroidRuntime(4985):     at android.app.ActivityThread.access$800(ActivityThread.java:138)
02-20 22:47:21.137: E/AndroidRuntime(4985):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1199)
02-20 22:47:21.137: E/AndroidRuntime(4985):     at android.os.Handler.dispatchMessage(Handler.java:102)
02-20 22:47:21.137: E/AndroidRuntime(4985):     at android.os.Looper.loop(Looper.java:136)
02-20 22:47:21.137: E/AndroidRuntime(4985):     at android.app.ActivityThread.main(ActivityThread.java:5050)
02-20 22:47:21.137: E/AndroidRuntime(4985):     at java.lang.reflect.Method.invokeNative(Native Method)
02-20 22:47:21.137: E/AndroidRuntime(4985):     at java.lang.reflect.Method.invoke(Method.java:515)
02-20 22:47:21.137: E/AndroidRuntime(4985):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
02-20 22:47:21.137: E/AndroidRuntime(4985):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
02-20 22:47:21.137: E/AndroidRuntime(4985):     at dalvik.system.NativeStart.main(Native Method)
02-20 22:47:21.137: E/AndroidRuntime(4985): Caused by: java.lang.ClassCastException: com.example.calculateday.ExampleActivity cannot be cast to android.app.Activity
02-20 22:47:21.137: E/AndroidRuntime(4985):     at android.app.Instrumentation.newActivity(Instrumentation.java:1061)
02-20 22:47:21.137: E/AndroidRuntime(4985):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2115)
02-20 22:47:21.137: E/AndroidRuntime(4985):     ... 11 more
我错了吗?我该怎么办?

1 个答案:

答案 0 :(得分:0)

使用PendingIntent.getBroadcast代替PendingIntent.getAcivity获取ExampleActivity的待定内容:

resultPendingIntent = PendingIntent.getBroadcast(this, 0, resultIntent,
            0);

因为ExampleActivityBroadcastReceiver而不是Activity