我的 AlarmService 只关闭了 3 秒

my AlarmService go off for only 3 sec

我正在使用闹钟管理器来设置和闹钟,它会在一天中使用服务的确切时间响起 但它只 运行 媒体播放器 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();
    }
}

您应该在 onStart() 方法中使用 startForeground(<notification id>, <notification>) 作为前台服务启动该服务。那么它的优先级会更高,被杀死的可能性也更小。参见 startForeground