【发布时间】:2018-03-04 14:41:03
【问题描述】:
我希望能够启动一项服务,或者让一个类在后台服务上运行,但我想访问我的 cordova 插件的类。
目前,我有一些类似于下面的东西,这不是很好,但它有效。但是如果用户将应用程序推到后面,或者关闭应用程序(而不是服务),那么它就会停止运行。
当用户关闭 UI 或退出应用程序时,我需要 MyHttpServer 继续运行。
public class MyCordovaPlugin extends CordovaPlugin {
private static final String TAG = "MyCordovaPlugin";
MyHttpServer httpServer;
@Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
if (httpServer == null) {
httpServer = new MyHttpServer();
}
if (action.equals("get-service-stats")) {
callbackContext.success(httpServer.getStats());
}
}
}
我知道要在后台运行服务,我可以使用以下代码,我现在为其他事情执行此代码并且它可以工作,但我无法从 cordova 访问实例。
// stop just encase its already started
context.stopService(new Intent(context, HttpServerService.class));
// start service
context.startService(new Intent(context, HttpServerService.class));
有没有一种特殊的方式来实现cordova插件和adnroid后台服务之间的通信?让我们说这个例子MyHttpServer作为它的一个方法叫做getStats,如果MyHttpServer在它自己的Service中运行,我怎么能在我的cordova插件中调用它。
像这样,这是插件
public class MyCordovaPlugin extends CordovaPlugin {
private static final String TAG = "MyCordovaPlugin";
@Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
if (action.equals("get-service-stats")) {
// CALL HttpServerService.GETSTATS METHOD HERE
}
}
}
这里是后台服务器
public class HttpServerService extends Service {
private static final String TAG = "HttpServerService";
private MyHttpServer httpServer;
private Context context;
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
context = this.getApplicationContext();
httpServer = new MyHttpServer();
httpServer.start();
return Service.START_STICKY;
}
public string getStats() {
return httpServer.getStats();
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
}
@Override
public void onDestroy() {
if (httpServer != null)
httpServer.stop();
super.onDestroy();
}
}
【问题讨论】:
标签: java android cordova ionic-framework phonegap