本教程来自android-er , 主 Activity (AndroidScheduledActivity.java)启动一个AlarmManager 来重复触发BroadcastReceiver(MyScheduledReceiver.java)。在 MyScheduledReceiver 的 onReceive() 方法中,它间接启动另一个 Activity (MyScheduledActivity.java)。这样 Activity (MyScheduledActivity.java)将在预定的时间间隔内启动。 现在我会使用 AutoStart 自动启动,但我无法编写 AutoStartNotifyReceiver 。 请你能给我一个如何管理它的想法吗? 非常感谢!
主要 Activity ,AndroidScheduledActivity.java:
public class AndroidScheduledActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button buttonStart = (Button)findViewById(R.id.start);
buttonStart.setOnClickListener(new Button.OnClickListener(){
@Override
public void onClick(View arg0) {
Intent myIntent = new Intent(getBaseContext(),
MyScheduledReceiver.class);
PendingIntent pendingIntent
= PendingIntent.getBroadcast(getBaseContext(),
0, myIntent, 0);
AlarmManager alarmManager
= (AlarmManager)getSystemService(ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.SECOND, 10);
long interval = 60 * 1000; //
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(), interval, pendingIntent);
finish();
}});
}
}
然后是BroadcastReceiver、MyScheduledReceiver.java
public class MyScheduledReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
Intent scheduledIntent = new Intent(context, MyScheduledActivity.class);
scheduledIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(scheduledIntent);
}
}
还有我的问题 AutoStartNotifyReceiver :
public class AutoStartNotifyReceiver extends BroadcastReceiver {
private final String BOOT_COMPLETED_ACTION = "android.intent.action.BOOT_COMPLETED";
@Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals(BOOT_COMPLETED_ACTION)){
????????????????????
}
}
}
最佳答案
您的 AutoStartNotifyReceiver extends BroadcastReceiver
类在那里,因为当设备重置时警报会被清除。因此,在此类的 onReceive
中(您有问号的地方),您需要使用相同的代码重新设置警报(当然没有 finish()
),你第一次在 AndroidScheduledActivity
的 onClick
方法中执行此操作。
然后,您需要将以下条目放入您的Manifest
中,让系统知道在系统启动时启动您的AutoStartNotifyReceiver
:
<receiver android:name=".AutoStartNotifyReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</receiver>
以及 Manifest
中的权限:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
现在,这一切都假设您只有一个闹钟并且每次只设置一种方式。如果情况并非如此,那么这会变得更加复杂。但根据您提供的少量信息,我的解决方案应该可以满足您的要求。
此外,由于您是这里的新手,因此请善意提醒:当有人对问题提供了充分的答案时,提出问题的人(您)会通过单击答案旁边的复选框来接受答案。这样回答的人就可以得到信任。欢迎来到 SO!
关于android - 如何自动启动 AlarmManager 以启动计划 Activity ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9386773/