我正在尝试在我的Android应用程序中启动和接近传感器服务,但代码只是似乎不起作用。代码运行有界命令,它也运行Localbinder。但该应用程序仍未显示接近传感器吐司。
这是我的代码。
public class proxy_service extends Service implements SensorEventListener {
private SensorManager mSensorManager;
private Sensor mProximity;
private static final int SENSOR_SENSITIVITY = 4;
@Nullable
public final IBinder b = new Localbinder();
@Override
public IBinder onBind(Intent intent) {
Log.w("this","started");
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mProximity = mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
Toast.makeText(getBaseContext(),"Sevice on bind",Toast.LENGTH_LONG).show();
return b;
}
public class Localbinder extends Binder
{
proxy_service getservice() throws InterruptedException{
Toast.makeText(getBaseContext(),"Sevice staaaaaarted",Toast.LENGTH_LONG).show();
return proxy_service.this;
}
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mProximity = mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
//mSensorManager.registerListener(this,mProximity,SensorManager.SENSOR_DELAY_NORMAL);
Toast.makeText(getBaseContext(),"Sevice staaaaaarted",Toast.LENGTH_LONG).show();
return START_STICKY;
}
@Override
public void onSensorChanged(SensorEvent event) {
if(event.sensor.getType() == Sensor.TYPE_PROXIMITY){
if (event.values[0] >= -SENSOR_SENSITIVITY && event.values[0] <= SENSOR_SENSITIVITY) {
//near
Toast.makeText(getBaseContext(), "near", Toast.LENGTH_SHORT).show();
} else {
//far
Toast.makeText(getBaseContext(), "far", Toast.LENGTH_SHORT).show();
}
}
mSensorManager.registerListener(this,mProximity,SensorManager.SENSOR_DELAY_NORMAL);
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
@Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this,"Sevice destroyed",Toast.LENGTH_LONG).show();
}
}
我还在清单文件中注册了我的代码
<service android:name=".proxy_service"></service>
这就是我在mainActivity中开始服务的方式
@Override
protected void onStart() {
super.onStart();
Intent i = new Intent(this,proxy_service.class);
bindService(i, connection, Context.BIND_AUTO_CREATE);
//startService(i);
//Toast.makeText(this,"",Toast.LENGTH_LONG).show();
}
private ServiceConnection connection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
proxy_service.Localbinder binder = (proxy_service.Localbinder) service;
try {
c= binder.getservice();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Override
public void onServiceDisconnected(ComponentName name) {
}