带有Alarmmanger的心跳无法使服务保持活力

时间:2018-09-06 08:41:31

标签: android service alarmmanager heartbeat

在May App中,我需要一项服务以在后台不断运行。我试图通过“警报管理器”的“心跳”来解决这个问题。它每隔15分钟调用一次AlarmReceive类,该类停止,然后再次启动Backround Service。 但是,当设备长时间不使用(大部分时间是晚上)时,系统会关闭所有设备 这是我的代码(MainActivity):

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Log.e("Alarmmanager", "Starting Alarmmanager");
    if (alarmManager == null && !isMyServiceRunning(BackroundService.class)) {
        alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        Intent intent = new Intent(this, AlarmReceive.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 900000, pendingIntent);
    }
}

和AlarmReceive:

public class AlarmReceive extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
    Intent background = new Intent(context, BackroundService.class);
    context.stopService(background);
    context.startService(background);

}
}

您能帮我解决这个问题吗? 我需要这项服务来朗读所有时间。 谢谢,斯拉蒂。

1 个答案:

答案 0 :(得分:0)

我被要求发布我的服务,该服务应在后台运行:

public class BackroundService extends Service {

boolean isDestroy;



@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}


@SuppressLint("MissingPermission")
@Override
public int onStartCommand(final Intent intent, int flags, int startId) {

    Log.e("New Service","################STARTED#################");

    isDestroy = false;

    //code for letting the service run even if app is not used
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        // For foreground service
        Intent notificationIntent = new Intent(this, BackroundService.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

        // Creating channel for notification
        String id = BackroundService.class.getSimpleName();
        String name = BackroundService.class.getSimpleName();
        NotificationChannel notificationChannel = new NotificationChannel(id,
                name, NotificationManager.IMPORTANCE_NONE);
        NotificationManager service = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        service.createNotificationChannel(notificationChannel);

        // Foreground notification
        Notification notification = new Notification.Builder(this, id)
                .setContentTitle(getText(R.string.app_name))
                .setContentText("KSL is protecting you!")
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentIntent(pendingIntent)
                .setTicker("Ticker text")
                .build();

        startForeground(9, notification);
    }

    //here is my locationlistener that's doing something with the gps updates



    return START_STICKY;
}



//this method request the gps location every 500 milliseconds, but only if the screen is turned on
public void requestingGpsUpdates(){
    powerManager = (PowerManager) this.getSystemService(Context.POWER_SERVICE);

    //Handler to delay
    new Handler().postDelayed(new Runnable() {
        @SuppressLint("MissingPermission")
        @Override
        public void run() {
        if (powerManager.isScreenOn()){
            Log.d("Requesting:","GpsLocation");
            //asking for a new update
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    //removing the update from before
                    Log.e("Updates:","removed");
                    locationManager.removeUpdates(locationListener);
                }
            },500);
            locationManager.requestLocationUpdates("gps", 0, 0, locationListener);
        }else{
            //if screen is turned off updates will be removed
            locationManager.removeUpdates(locationListener);
        }
        //the method calling itself for a loop
            if (!isDestroy){
                requestingGpsUpdates();
            }else {
            Log.e("Service", "get's destroyed!");
            }
        }
    },500);
}

@Override
public void onDestroy() {
    super.onDestroy();
    locationManager.removeUpdates(locationListener);
    isDestroy = true;
}

}