我正在使用警报管理器来设置和警报在一天中的确切时间使用服务
但它只能运行mediaplayer 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;
        }
}


主要活动

  @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();
    }
}

最佳答案

您应该在startForeground(<notification id>, <notification>)方法中使用onStart()将服务作为前台服务启动。然后,它将具有更高的优先级,并且不太可能被杀死。请参见startForeground

关于android - 我的AlarmService熄灭仅3秒钟,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49459526/

10-09 04:57