5

我发现了很多与此类似的问题,但至少我认为它们太复杂了(代码太多)。

这件事可以用几行代码完成吗?我想在 10(比方说)分钟内启动一项活动,就是这样。谢谢你。

4

2 回答 2

3

设置警报 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>
于 2012-07-26T14:03:55.647 回答
1

我使用的此功能根据“设置”参数设置或取消警报

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

}

于 2012-07-26T13:48:02.897 回答