如何使用Alarmmanager触发广播接收器?

时间:2014-03-16 06:45:19

标签: android broadcastreceiver alarmmanager

我是一个新手Android,我正在开发一个应用程序,我想在每5分钟后向我发送一条消息。我正在使用广播接收器。我想使用Alarmmanager来触发广播接收器。我希望这个应用程序只在后台运行。 谁能建议我一步一步做什么?我的代码如下:

     public class k extends BroadcastReceiver{

@SuppressLint("NewApi")
@Override
public void onReceive(Context context, Intent arg1) {
    // TODO Auto-generated method stub


     Toast.makeText(context, "in android.location.PROVIDERS_CHANGED",
                Toast.LENGTH_SHORT).show();
    Intent broadcast = new Intent(context, k.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, broadcast, 0);

    AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    alarmManager.setRepeating(getResultCode(), 1000,10, pendingIntent);
     Toast.makeText(context, "in android.location.PROVIDERS_CHANGED",
                Toast.LENGTH_SHORT).show();

}

}

2 个答案:

答案 0 :(得分:0)

Intent broadcast = new Intent(context, gpsbroad.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, broadcast, 0);

AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.setExact(alarmType, triggerAtMillis, pendingIntent);

PendingIntent:https://developer.android.com/reference/android/app/PendingIntent.html

AlarmManager:https://developer.android.com/reference/android/app/AlarmManager.html

答案 1 :(得分:0)

尝试使用它:

public static AlarmManager am;
public static PendingIntent sender;


Intent intent1 = new Intent(thisActivity, gpsbroad.class);
sender = PendingIntent.getBroadcast(thisActivity, 2, intent1,0);
am = (AlarmManager) getSystemService(ALARM_SERVICE);
long l = new Date().getTime();
if (l < new Date().getTime()) {
    l += 100;
}
am.setRepeating(AlarmManager.RTC_WAKEUP, l, 100, sender);