AlarmManager 每天上午 9 点通知服务和广播

AlarmManager Notification daily 9 AM with service and broadcast

这是每天下午 5 点 15 分设置闹钟的方法

我正在调用 setAlarm() 方法,当我的应用程序首先启动时 time.App 打开 (First Launch time) 那时自动 Notification 生成并不断地再次触发相同的通知 n 和interval time 大约 2 min

注意 : 生成通知不是问题。

 public void setAlarm() {
    alarmManager = (AlarmManager) getActivity().getSystemService(ALARM_SERVICE);

    alarmIntent = new Intent(getActivity(), AlarmReceiver.class);
    pendingIntent = PendingIntent.getBroadcast(getActivity(), 0, alarmIntent, 0);

    Calendar calendar = Calendar.getInstance();

    calendar.setTimeInMillis(System.currentTimeMillis());
    calendar.set(Calendar.HOUR_OF_DAY, 17);
    calendar.set(Calendar.MINUTE, 15);
    alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
    //alarmManager.setRepeating(AlarmManager.RTC, AlarmManager.INTERVAL_HALF_DAY, AlarmManager.INTERVAL_HALF_DAY, pendingIntent);

}

报警服务

public class AlarmReceiver extends BroadcastReceiver {

NotificationManager notificationManager;

@Override
public void onReceive(Context context, Intent intent) {
    Intent service1 = new Intent(context, MyAlarmService.class);
    context.startService(service1);
}
}

我的报警服务

public class MyAlarmService extends Service {
private static final int NOTIFICATION_ID = 1;
private NotificationManager notificationManager;
private PendingIntent pendingIntent;
private ArrayList<RandomQuotes> randomQuotesArrayList;
private PrefManager prefManager;

@Override
public IBinder onBind(Intent arg0) {
    return null;
}

@SuppressWarnings("static-access")
@Override
public void onStart(Intent intent, int startId) {
    super.onStart(intent, startId);
    Context context = this.getApplicationContext();
    prefManager = new PrefManager(this);
    randomQuotesArrayList = prefManager.getSharedPreferenceStringList(this, "quote");
    notificationManager = (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);
    Intent mIntent = new Intent(this, MainActivity.class);
    pendingIntent = PendingIntent.getActivity(context, 0, mIntent, PendingIntent.FLAG_CANCEL_CURRENT);
    NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
    builder.setVibrate(new long[]{5, 5, 5, 5, 5});

    builder.setLights(Color.RED, 3, 3);
    builder.setContentTitle("Quote Of the Day");
    builder.setContentText(randomQuotesArrayList.get(0).getRandomQuote() + "\n\n" + "-" + randomQuotesArrayList.get(0).getRandomQuoteAuthor());
    String longText;
    if (!randomQuotesArrayList.get(0).getRandomQuoteAuthor().isEmpty()) {
        longText = randomQuotesArrayList.get(0).getRandomQuote() + "\n\n" + " -" + randomQuotesArrayList.get(0).getRandomQuoteAuthor();
    } else {
        longText = randomQuotesArrayList.get(0).getRandomQuote() + "\n" +randomQuotesArrayList.get(0).getRandomQuoteAuthor();
    }
    builder.setStyle(new NotificationCompat.BigTextStyle().bigText(longText));
    builder.setSmallIcon(R.drawable.qt);
    builder.setContentIntent(pendingIntent);
    builder.setDefaults(Notification.DEFAULT_SOUND)
            .setDefaults(Notification.DEFAULT_ALL).setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
    ;
    notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    notificationManager.notify(NOTIFICATION_ID, builder.build());
}
}

对于每日行情,我做了一些事情....

public void setAlarm() {
    // Quote in Morning at 08:32:00 AM
        Calendar calendar = Calendar.getInstance();

        calendar.set(Calendar.HOUR_OF_DAY, 8);
        calendar.set(Calendar.MINUTE, 32);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);

        Calendar cur = Calendar.getInstance();

        if (cur.after(calendar)) {
            calendar.add(Calendar.DATE, 1);
        }

        Intent myIntent = new Intent(context, DailyReceiver.class);
        int ALARM1_ID = 10000;
        PendingIntent pendingIntent = PendingIntent.getBroadcast(
                context, ALARM1_ID, myIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);

}

并获得这个接收器

public class DailyReceiver extends BroadcastReceiver {
DatabaseHelper databaseHelper;

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

    String quote ;

    long when = System.currentTimeMillis();
    NotificationManager notificationManager = (NotificationManager) context
            .getSystemService(Context.NOTIFICATION_SERVICE);

    Intent notificationIntent = new Intent(context, DailySpecialActivity.class);
    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pendingIntent = PendingIntent.getActivity(context, 0,
            notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);

    Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

    // get your quote here
    quote = doSomeMethod();


    NotificationCompat.Builder mNotifyBuilder = new NotificationCompat.Builder(
            context).setSmallIcon(R.mipmap.ic_launcher)
            .setContentTitle("My Quotes")
            .setContentText(quote).setSound(alarmSound)
            .setAutoCancel(true).setWhen(when)
            .setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher))
            .setStyle(new NotificationCompat.BigTextStyle().bigText(quote))
            .setContentIntent(pendingIntent)
            .setVibrate(new long[]{1000, 1000, 1000, 1000, 1000});  // Declair VIBRATOR Permission in AndroidManifest.xml
    notificationManager.notify(5, mNotifyBuilder.build());
  }

}

这里当你重启你的 phone 你也需要重启你的闹钟,所以我已经做了

public class WakeUpAlarmReceiver extends BroadcastReceiver {

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

    if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED")) {

        // Quote in Morning

        Calendar calendar = Calendar.getInstance();

        calendar.set(Calendar.HOUR_OF_DAY, 8);
        calendar.set(Calendar.MINUTE, 30);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);

        Calendar cur = Calendar.getInstance();

        if (cur.after(calendar)) {
            calendar.add(Calendar.DATE, 1);
        }

        Intent myIntent = new Intent(context, DailyReceiver.class);
        int ALARM1_ID = 10000;
        PendingIntent pendingIntent = PendingIntent.getBroadcast(
                context, ALARM1_ID, myIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);

      }
   }
}

你的AndroidManifest.xml

终于来了
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.nils.myquotesapp">
<!--you must need this three permissions-->
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.VIBRATE" />


<application
    android:name="com.nils.myquotesapp.QuotesApplication"
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:largeHeap="true"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">

    <activity
        android:name="com.nils.myquotesapp.Activity.MainActivity"
        android:label="@string/app_name"
        android:screenOrientation="portrait"
        android:theme="@style/AppTheme.NoActionBar">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <receiver
        android:name="com.nils.myquotesapp.DailyReceiver"
        android:enabled="true" />

    <receiver
        android:name="com.nils.myquotesapp.WakeUpAlarmReceiver"
        android:enabled="true">
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED" />
            <category android:name="android.intent.category.DEFAULT" />
            <action android:name="android.intent.action.QUICKBOOT_POWERON" />
        </intent-filter>
    </receiver>

</application>
<meta-data
    android:name="com.google.android.gms.version"
    android:value="@integer/google_play_services_version" />
</manifest>

永远祝你好运兄弟..!!

您也可以使用以下服务执行这些日常任务,例如警报管理器和其他任务。

以下内容可能更有用,电池效率更高,使用更优化。

1:作业计划

2:调度执行器服务

虽然它由 android 支持库提供,但您可以在 Internet 上找到非常有用的示例。

快乐编码:)