出于设计原因,我必须使用extends Service
将特定于Android传感器的代码实现到类中。例如,
public class SmokeService extends Service implements ISmokeDetector {
SensorManager mySensorManager;
Sensor myProximitySensor;
private double currentLightReading;
private Context myContext;
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
@Override
public void onCreate() {
super.onCreate();
mySensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
myProximitySensor = mySensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
mySensorManager.registerListener(proximitySensorEventListener, myProximitySensor, SensorManager.SENSOR_DELAY_NORMAL);
}
SensorEventListener proximitySensorEventListener = new SensorEventListener() {
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}
@Override
public void onSensorChanged(SensorEvent event) {
}
};
@Override
public SmokePresenceStruct getsmokePresence() {
return new SmokePresenceStruct(true, timestamp);
}
@Override
public void getsmokePresence(ListenersmokePresence handler) {
handler.onNewsmokePresence(this.getsmokePresence());
}
@Override
public boolean isEventDriven() {
}
}
我的问题是“有没有办法通过非Android Java类启动上述服务?”假设我有一个java类,谁有Context,它想要启动这项服务。例如:
public class AndroidSmokeDetector {
Context myContext;
public AndroidSmokeDetector(Context context, Object obj) {
//super(context);
this.myContext = context;
}
}
请告诉我通过AndroidSmokeDetector
课程与服务互动的方式。假设我将从MainActivity
得到上下文?“
答案 0 :(得分:1)
是的,你的AndroidSmokeDetector只需调用
myContext.startService(myContext, SmokeService.class);
答案 1 :(得分:0)
有没有办法通过非Android Java启动上述服务 类?
选项1:
是的,你需要使用类构造函数来获取非Activity类中的Context.do it as:
public class AndroidSmokeDetector {
Context myContext;
public AndroidSmokeDetector(Context context, Object obj) {
//super(context);
this.myContext = context;
}
//...
}
使用myContext
从AndroidSmokeDetector
类启动服务:
myContext.startService(myContext, SmokeService.class);
使用MainActivity
类构造函数发送AndroidSmokeDetector
活动上下文:
AndroidSmokeDetector objsmokeclass=new AndroidSmokeDetector(MainActivity.this);
选项2:
而不是使用类构造函数,您可以创建一个参数化方法,用于从非Activity类启动Service.as:
public class AndroidSmokeDetector {
public void startServiceFromNonActivityClass(Context myContext){
//start service here...
myContext.startService(myContext, SmokeService.class);
}
//...
}
现在只需通过从Activity传递当前上下文来调用启动服务的方法:
AndroidSmokeDetector objsmokeclass=new AndroidSmokeDetector();
objsmokeclass.startServiceFromNonActivityClass(MainActivity.this);