0

出于设计原因,我必须在类中实现 Android 传感器特定代码extends Service。例如,

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?”

4

2 回答 2

1

是的,在您的 AndroidSmokeDetector 中只需调用

myContext.startService(myContext, SmokeService.class);
于 2013-05-06T17:30:36.880 回答
0

有没有办法通过非Android Java 类启动上述服务?

选项1 :

是的,您将需要使用类构造函数在非 Activity 类中获取 Context。按以下方式执行:

public class AndroidSmokeDetector {
    Context myContext;

    public AndroidSmokeDetector(Context context, Object obj) {
        //super(context);
        this.myContext = context;
    }
 //...
}

用于myContextAndroidSmokeDetector类开始服务:

myContext.startService(myContext, SmokeService.class);

MainActivity使用AndroidSmokeDetector类构造函数发送活动上下文:

AndroidSmokeDetector objsmokeclass=new AndroidSmokeDetector(MainActivity.this);

选项 2:

您可以创建一个参数化方法来从非 Activity class.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);
于 2013-05-06T17:36:49.813 回答