简单AlarmManager例如,对于在10分钟内射击活动(Simple AlarmManager

2019-06-26 13:54发布

我发现这个很多类似的问题,但他们太复杂(太多的代码),至少我这样认为。

可这件事情中的行数代码来完成? 我想火在10活动(比方说)分钟,仅此而已。 谢谢。

Answer 1:

本博客文章介绍正是你所期待的。



Answer 2:

到10分钟,设置闹钟(比方说)使用此代码

 AlarmManager alarmMgr = (AlarmManager)getSystemService(ALARM_SERVICE);
 Intent intent = new Intent(this, ShortTimeEntryReceiver.class);   
 PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0,  intent, PendingIntent.FLAG_UPDATE_CURRENT);
 alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),10*60*1000, pendingIntent); 

要启动活动

public class ShortTimeEntryReceiver extends BroadcastReceiver{


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

 try {
         Bundle bundle = intent.getExtras();
         String message = bundle.getString("alarm_message");

         // Your activity name
         Intent newIntent = new Intent(context, ReminderPopupMessage.class); 
         newIntent.putExtra("alarm_message", message);
         newIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);  
         context.startActivity(newIntent);
        } catch (Exception e) { 
         e.printStackTrace();

        } 
} 
}

在您的清单文件中添加以下

 <receiver android:name=".ShortTimeEntryReceiver"
                      android:enabled="true"
                      android:process=":remote"> 
            </receiver>


Answer 3:

这个功能我用的设定或取消根据“设置”参数报警

public static void SetAlarm(Context c, long AlarmTime, int ItemID, String Message, Boolean Set) {
    Intent intent = new Intent(c, AlarmReceiver.class);
    intent.putExtra("Message", Message);
    intent.putExtra("ItemID", ItemID);

    PendingIntent sender = PendingIntent.getBroadcast(c, 8192 + ItemID, intent, PendingIntent.FLAG_UPDATE_CURRENT);

            // Clear the seconds to 0 for neatness
    Calendar ca = Calendar.getInstance();
    ca.setTimeInMillis(AlarmTime);
    ca.set(Calendar.SECOND, 0);
    AlarmTime = ca.getTimeInMillis();

    // Get the AlarmManager service
    AlarmManager am = (AlarmManager) c.getSystemService(Context.ALARM_SERVICE);
    if (Set) {
        am.set(AlarmManager.RTC_WAKEUP, AlarmTime, sender);
    } else {
        am.cancel(sender);
    }
}

那么你就需要一个广播接收器来处理报警,做什么是你想做的事情。

public class AlarmReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
    try {
        Bundle bundle = intent.getExtras();
        String Message = bundle.getString("Message");
        int ItemID = bundle.getInt("ItemID");

        // Do what you want to do, start an activity etc

    } catch (Exception e) {
        e.printStackTrace();
    }
}

}



文章来源: Simple AlarmManager example for firing an activity in 10 minutes