Android 如何使用Alarmmanager触发广播接收器?
我是一个Android新手,我正在开发一个应用程序,在这个应用程序中,我想每5分钟干杯一次。我正在使用一个广播接收器。我想使用Alarmmanager触发广播接收器。我希望此应用程序仅在后台运行。 谁能建议我一步一步地做什么?我的代码如下:Android 如何使用Alarmmanager触发广播接收器?,android,broadcastreceiver,alarmmanager,Android,Broadcastreceiver,Alarmmanager,我是一个Android新手,我正在开发一个应用程序,在这个应用程序中,我想每5分钟干杯一次。我正在使用一个广播接收器。我想使用Alarmmanager触发广播接收器。我希望此应用程序仅在后台运行。 谁能建议我一步一步地做什么?我的代码如下: public class k extends BroadcastReceiver{ @SuppressLint("NewApi") @Override public void onReceive(Context context, Intent a
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();
}
}
悬垂物:
AlarmManager:尝试使用以下方法:
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);
公共静态报警管理器am;
公共静态悬挂发送器;
意向意向1=新意向(此活动,gpsbroad.class);
sender=PendingEvent.getBroadcast(此活动,2,意图1,0);
am=(AlarmManager)getSystemService(报警服务);
长l=新日期().getTime();
if(l
我不想开始任何活动..我只想在每次时间变化时显示祝酒词。请检查我编辑的代码添加新活动,并在其中显示toast,如下所示:公共类AlarmReceiver扩展BroadcastReceiver{@Override public void onReceive(上下文上下文,意图意图){toast.makeText(上下文,“报警触发”,toast.LENGTH_LONG).show();}我只想让它在后台运行,因为我正在开发的应用程序要求它在安装时只在后台运行1。什么是getResultCode()
?此参数需要是AlarmManager指定的类型之一:已用实时、已用实时唤醒、RTC或RTC唤醒。2.值1000是错误的。你需要在将来的某个地方得到时间的价值。根据您选择的报警类型(请参见#1),您可以从System.currentTimeMillis()
或SystemClock.elapsedRealtime()
或从日期
或日历
对象派生的对象开始。3.您使用10毫秒作为重复间隔,这太短了。
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);