我正在开发一个应用程序来监视接近传感器值的变化。在应用程序中应该有两个单独的按钮来启动服务,然后开始监视接近传感器。
这是我的服务等级
public class MyService extends Service{
Sensor proxSensor;
SensorManager sm;
public static MyService instance;
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
instance = this;
return Service.START_STICKY;
}
public void startScan(){
sm=(SensorManager)getSystemService(SENSOR_SERVICE);
proxSensor=sm.getDefaultSensor(Sensor.TYPE_PROXIMITY);
SensorEventListener eventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent sensorEvent) {
Log.e("Sensor","Value "+sensorEvent.values[0]);
}
@Override
public void onAccuracyChanged(Sensor sensor, int i) {
}
};
sm.registerListener(eventListener, proxSensor, SensorManager.SENSOR_DELAY_NORMAL);
}
我正在从我的主要 Activity 开始服务
public void viewNotification(View view){
startService(new Intent(this,MyService.class));
}
public void viewNotification2(View view){
MyService.instance.startScan();
}
应用程序运行时,日志输出可以正确打印,但是当我关闭 Activity 并将其从以前的应用程序列表中删除时,未给出输出。但是,如果我在 onStartCommand 中调用 startScan() ,即使我关闭应用程序,它也会继续运行。
为什么它不继续给出输出? 除了使用静态 MyService 之外,还有其他方法来实现此目的吗?
最佳答案
首先 - 使用服务绑定(bind)或 aidl 方法来使用您的服务。 (参见:https://developer.android.com/guide/components/bound-services.html)
例如:
假设,我们有名为 MyService 的服务。 在这个类中你需要写下一个
private final IBinder mBinder = new LocalServiceBinder();
@Nullable
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
public class LocalServiceBinder extends Binder {
public MyService getBinder() {
return MyService.this;
}
}
您的 Activity 中的下一个:
private MyService mService;
boolean isBounded;
private ServiceConnection mServiceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
Log.d(TAG, "onServiceConnected");
MyService.LocalServiceBinder binder = (MyService.LocalServiceBinder) service;
mService = binder.getBinder();
isBounded = true;
}
@Override
public void onServiceDisconnected(ComponentName name) {
Log.d(TAG, "onServiceDisconnected");
isBounded = false;
}
};
和
@Override
protected void onStart() {
super.onStart();
bindService(new Intent(this, MyService.class), mServiceConnection, BIND_AUTO_CREATE);
}
@Override
protected void onStop() {
super.onStop();
if (isBounded) {
unbindService(mServiceConnection);
isBounded = false;
}
}
现在您可以调用您的服务方法,例如:
private void activityMethod(){
if (isBounded){
mService.someMethod();
}
}
其次,如果要在前台工作,请调用startForeground(int id,Notification notification)方法。
关于java - 调用Android启动服务中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46154239/