How to create plugin in phonegap to run the application in background?

前端 未结 2 1142
难免孤独
难免孤独 2020-12-08 06:13

I have created plugin for background service (to run the application in background) in phonegap.

here is my java code for plugin:

public class Backgr         


        
相关标签:
2条回答
  • 2020-12-08 06:18

    Creation of plugin is fine.You create your service just like a normal java file. And then As soon as you call this plugin . you just start your service like

    startService(new Intent(this, MyService.class));
    

    Then your service will run in background.This is an easy way to do.

    If separately you create service then

    Your Plugin should look like this

    public class BackgroundService extends Plugin {
    
    private static final String TAG = "BackgroundService";
    private static final String CALL_SERVICE_ACTION = "callService";
    
    @Override
    public PluginResult execute(String action, JSONArray args, String callbackId)
    {
        Log.i(TAG, "Plugin Called");
    PluginResult result = null;
    
    if (CALL_SERVICE_ACTION.equals(action)) {
        Log.d(TAG, "CALL_SERVICE_ACTION");
        startService(new Intent(ctx, MyService.class));
    }
    
    else {
        result = new PluginResult(Status.INVALID_ACTION);
        Log.d(TAG, "Invalid action : " + action + " passed");
    }
    
    return result;
    }
    }
    

    Your .js file should look like this

    function BackgroundService() {
    };
    
    BackgroundService.prototype.callService = function(successCallback, failCallback) {
    
    return PhoneGap.exec(successCallback, failCallback, "BackgroundService",
        "callService", [ null ]);
    };
    
    PhoneGap.addConstructor(function() {
    PhoneGap.addPlugin("BackgroundService", new BackgroundService());
    });
    

    And your HTML file should look like this

    function callServiceFunction() {
    window.plugins.BackgroundService.callService('callService',
            callServiceSuccessCallBack, callServiceFailCallBack);
    
    }
    function callServiceSuccessCallBack(e) {
    alert("Success");
    }
    
    function callServiceFailCallBack(f) {
    alert("Failure");
    }
    

    Also you need to register your phonegap plugin in your res/xml/plugins.xml like

    <plugin name="BackgroundService" value="package-structure.BackgroundService"/>
    
    0 讨论(0)
  • 2020-12-08 06:37

    In the onCreate method of your Java class that extends from DroidGap make sure you have set "keepRunning" properly.

            super.setBooleanProperty("keepRunning", true);
    
    0 讨论(0)
提交回复
热议问题