我使用报警管理器设置和报警,使用服务在一天中的确切时间内关闭 但它只运行媒体播放器3秒钟并终止服务, 如果我在警报歌曲运行时滑动应用程序,服务终止
//当我使用TimePicker而不是自己设置时间时,闹钟立即熄灭3秒然后停止,并且在我使用TimePicker选择的确切时间内,闹钟完美地运行
<manifest
<uses-permission android:name="android.permission.WAKE_LOCK" />
<service
android:name=".Service"
android:exported="false" />
服务
public class Service extends android.app.Service {
@Override
public IBinder onBind(Intent arg0) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
MediaPlayer mediaPlayer = MediaPlayer.create(this, R.raw.rev);
mediaPlayer.start();
return START_STICKY;
}
}
MainActivity
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR, 2018);
calendar.set(Calendar.MONTH, 2);
calendar.set(Calendar.DAY_OF_MONTH, 24);
calendar.set(Calendar.HOUR_OF_DAY, 1);
calendar.set(Calendar.MINUTE, 4);
calendar.set(Calendar.SECOND, 0);
setAlarm(calendar.getTimeInMillis());
}
private void setAlarm(long time) {
Intent i = new Intent(this, Service.class);
PendingIntent pendingIntent = PendingIntent.getService(this, 0, i, 0);
AlarmManager am = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
int ALARM_TYPE = AlarmManager.RTC_WAKEUP;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
am.setExactAndAllowWhileIdle(ALARM_TYPE, time, pendingIntent);
else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
am.setExact(ALARM_TYPE, time, pendingIntent);
else
am.set(ALARM_TYPE, time, pendingIntent);
Toast.makeText(this, "Alarm is set", Toast.LENGTH_SHORT).show();
}
}
答案 0 :(得分:0)
您应该使用startForeground(<notification id>, <notification>)
方法中的onStart()
将服务作为前台服务启动。然后它将具有更高的优先级,并且不太可能被杀死。请参阅startForeground。