Android中监听系统时间改变及开机广播后通过AlarmManager进行通知

1. 当时间发生改变时,进行广播通知

public class TimeChangedReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {

        if ("android.intent.action.TIME_SET".equals(intent.getAction())) {
            // 实际应用是从数据库中获取数据
            SharedPreferences pref = context.getSharedPreferences("MyPref", Context.MODE_PRIVATE);
            long timeInMilli = pref.getLong("timeInMilli", 1);
            Utils.setAlarm(context, timeInMilli);
        }

    }
}

 清单文件配置


    
         
    

2. 监听开机广播

public class BootCompleteReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {

        if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) {
            // 实际应用是从数据库中获取数据
            SharedPreferences pref = context.getSharedPreferences("MyPref", Context.MODE_PRIVATE);
            long timeInMilli = pref.getLong("timeInMilli", 1);
            Utils.setAlarm(context, timeInMilli);
        }

    }
}

 清单文件配置



        
            
                
            
        

3. 通过notification进行广播

public class NotificationReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {

        NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            // Create the NotificationChannel
            String name = "Alarm";
            String descriptionText = "Alarm detail";
            int importance = NotificationManager.IMPORTANCE_DEFAULT;
            NotificationChannel mChannel = new NotificationChannel("AlarmId", name, importance);
            mChannel.setDescription(descriptionText);
            if (notificationManager != null) {
                notificationManager.createNotificationChannel(mChannel);
            }

        }

        // Create the notification to be shown
        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context, "AlarmId")
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle("Alarm")
                .setContentText("Here\'s your alarm!")
                .setAutoCancel(true)
                .setPriority(NotificationCompat.PRIORITY_DEFAULT);

        int id = (int) (System.currentTimeMillis() / 1000);

        if (notificationManager != null) {
            notificationManager.notify(id, mBuilder.build());
        }

    }
}

 清单文件配置

Utils.java 工具类

public class Utils {

    public static void setAlarm(Context context, long timeOfAlarm) {

        Intent broadcastIntent = new Intent(context, NotificationReceiver.class);

        PendingIntent pIntent = PendingIntent.getBroadcast(
                context, 0, broadcastIntent, 0
        );

        AlarmManager alarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);

        if (System.currentTimeMillis() < timeOfAlarm) {
            if (alarmMgr != null) {
                alarmMgr.set(AlarmManager.RTC_WAKEUP, timeOfAlarm, pIntent);

                // 非重复闹铃设置
//                alarmMgr.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
//                        SystemClock.elapsedRealtime() + 60 * 1000,
//                        pIntent
//                );
                // 重复性闹铃设置
                alarmMgr.setInexactRepeating(
                        AlarmManager.RTC_WAKEUP,
                        timeOfAlarm,
                        AlarmManager.INTERVAL_DAY,
                        pIntent
                );
            }
        }
    }
}

Activity 中 

public class MainActivity extends AppCompatActivity {

    private TextView mStartTimeText;
    private long timeInMilliSeconds;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ComponentName receiver = new ComponentName(getApplication(), BootCompleteReceiver.class);

        getApplication().getPackageManager().setComponentEnabledSetting(receiver,
                PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
                PackageManager.DONT_KILL_APP);

        mStartTimeText = findViewById(R.id.startTimeText);
        mStartTimeText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final Calendar calendar = Calendar.getInstance();
                int hour = calendar.get(Calendar.HOUR_OF_DAY);
                int minute = calendar.get(Calendar.MINUTE);

                TimePickerDialog timePickerDialog = new TimePickerDialog(MainActivity.this, new TimePickerDialog.OnTimeSetListener() {
                    @Override
                    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                        calendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
                        calendar.set(Calendar.MINUTE, minute);
                        calendar.set(Calendar.SECOND, 0);

                        String amPm = "";
                        if (hourOfDay < 12) {
                            amPm = "am";
                        } else {
                            amPm = "pm";
                        }

                        String formattedTime = String.format(Locale.getDefault(), "%02d:%02d %s", hourOfDay, minute, amPm);
                        mStartTimeText.setText(formattedTime);

                        SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss", Locale.getDefault());
                        String formattedDate = sdf.format(calendar.getTime());
                        Date date;
                        try {
                            date = sdf.parse(formattedDate);
                            timeInMilliSeconds = date.getTime();
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }
                    }
                }, hour, minute, false);

                timePickerDialog.show();
            }
        });

        findViewById(R.id.setAlarm).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (timeInMilliSeconds != 0) {
                    Toast.makeText(MainActivity.this, "Alarm has been set!", Toast.LENGTH_LONG).show();

                    SharedPreferences pref = getSharedPreferences("MyPref", Context.MODE_PRIVATE);
                    pref.edit().putLong("timeInMilli", timeInMilliSeconds).apply();

                    Utils.setAlarm(getApplication(), timeInMilliSeconds);

                } else {
                    Toast.makeText(MainActivity.this, "Please enter the time first!", Toast.LENGTH_LONG).show();

                }
            }
        });

    }
}

 

你可能感兴趣的:(android,基础)