繁体   English   中英

从Cordova插件调用后台服务方法

[英]Call background service method from cordova plugin

我希望能够启动服务,或者让类在后台服务上运行,但是我想访问该类的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();
    }
}

有没有一种特定的方法来实现cordova插件和adnroid后台服务之间的通信? 对于本示例,假设MyHttpServer作为其上的一种名为getStats的方法,如果MyHttpServer在其自己的Service中运行,该如何在我的cordova插件中调用它?

您可以使用此开发人员指南在您的活动和服务之间实现绑定。 这样,您就可以从活动中调用服务的方法。

目前,我有一些类似于下面的内容,虽然不是很好,但是它可以工作。 但是,如果用户将应用程序向后推或关闭该应用程序(而非服务),则它将停止运行。

如果您希望服务运行,则它必须是前台服务,即使您的活动将被停止。 您应该看到此前台服务实现示例 您必须知道Oreo在后台执行方面有一些限制

对不起我的英语不好

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM