我在Android中有一项服务。我想每天早上8点到晚上8点运行这项服务。如何在Android Application.Aready我的服务使用Broadcastreceiver BootUp事件在BootUp上启动。如何做到这一点?
答案 0 :(得分:1)
为此,您需要使用AlarmManager
类。只需在您想要重复的闹钟中注册您的活动/服务即可。并开始报警。
答案 1 :(得分:1)
我已经尝试过如下的闹钟管理器。我想在早上8点开始...但是它没有在早上8点启动应用程序。但是所有Toast消息显示......
<强> AlarmReceiver.class 强>
public class AlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Alarm Receiver", Toast.LENGTH_LONG).show();
AlarmManager alarm=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(context, MyService.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, i, 0);
Calendar time = Calendar.getInstance();
//time.setTimeInMillis(System.currentTimeMillis());
time.add(Calendar.MINUTE, 8);
time.add(Calendar.HOUR, 0);
time.add(Calendar.SECOND, 0);
Toast.makeText(context, "App will start shortly", Toast.LENGTH_LONG).show();
Toast.makeText(context, time.toString(), Toast.LENGTH_LONG).show();
alarm.set(AlarmManager.RTC_WAKEUP, time.getTimeInMillis(), pendingIntent);
}
}
<强> manifest资源配置文件:强>
</application>
<receiver android:name="AlarmReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
</application>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<uses-permission android:name="android.permission.SET_TIME"/>