运行 没有 Activity 的 IntentService
Run an IntentService without an Activity
我有一个服务需要在后台永久 运行,但是一旦 activity 关闭,它创建的 IntentService 也会关闭:
public class CAS extends IntentService {
public CAS() {
super("CAS");
}
Sensor accelerometer;
SensorManager sensorManager;
CA cA= new CA();
@Override
protected void onHandleIntent(@Nullable Intent intent) {
sensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
sensorManager.registerListener(cA, accelerometer, SensorManager.SENSOR_DELAY_FASTEST);
LocationManager locationManager = GlobalFunctions.LocationLibrary.getLocationManager(this);
cA.start(this, locationManager);
}
}
我怎样才能让这个 class 运行 无限期地在后台运行,甚至在 Android 启动时启动?
您需要使用 BroadcastReceiver 注册服务
这里有一个 sample 程序。
检查 this 设备重启时重启服务的答案
Documentation 的 BroadcastReceiver
我有一个服务需要在后台永久 运行,但是一旦 activity 关闭,它创建的 IntentService 也会关闭:
public class CAS extends IntentService {
public CAS() {
super("CAS");
}
Sensor accelerometer;
SensorManager sensorManager;
CA cA= new CA();
@Override
protected void onHandleIntent(@Nullable Intent intent) {
sensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
sensorManager.registerListener(cA, accelerometer, SensorManager.SENSOR_DELAY_FASTEST);
LocationManager locationManager = GlobalFunctions.LocationLibrary.getLocationManager(this);
cA.start(this, locationManager);
}
}
我怎样才能让这个 class 运行 无限期地在后台运行,甚至在 Android 启动时启动?
您需要使用 BroadcastReceiver 注册服务
这里有一个 sample 程序。
检查 this 设备重启时重启服务的答案
Documentation 的 BroadcastReceiver