嗨朋友我需要每天早上6点开始服务,并且需要每天早上8点停止服务,请任何人帮助我如何实现这一目标..
答案 0 :(得分:1)
是的,您可以在AlarmManager
的帮助下完成此操作public class AlarmReceiver extends BroadcastReceiver
{
@Override
public void onReceive(Context context, Intent intent)
{
Toast.makeText(context, "Alarm Receiver", Toast.LENGTH_LONG).show();
}
public void setAlarm(Context context, Calendar cal1,String name)
{
AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, AlarmReceiver.class);
intent.putExtra("name", name);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_ONE_SHOT);
final Calendar c = Calendar.getInstance();
long interval = cal1.getTimeInMillis() - c.getTimeInMillis();
Toast.makeText(context, "Interval=" + interval, Toast.LENGTH_LONG).show();
Log.d("debug", "" + interval);
Log.d("debug", "Current miliseconds =" + c.getTimeInMillis());
am.set(AlarmManager.RTC, cal1.getTimeInMillis(), pi);
}
public void CancelAlarm(Context context)
{
Intent intent = new Intent(context, AlarmReceiver.class);
PendingIntent sender = PendingIntent.getBroadcast(context, 0, intent, 0);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(sender);
}
}
这是班级
您可以使用此类直接设置闹钟 (不要忘记在AndroidManifest.xml中包含接收器)
希望这会对你有所帮助
答案 1 :(得分:0)
创建 BroadcastReceiver
public class MyReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (action.equals(Intent.ACTION_TIME_CHANGED) ||
action.equals(Intent.ACTION_TIMEZONE_CHANGED))
{
// get the current time here and start/stop your sevice depend on the time
}
}
}