使用phonegap打开Android位置设置

Dav*_*vid 5 android geolocation phonegap-plugins cordova

我通过phonegap使用用户的地理位置.这个例子如下所示.(机器人)

  // onSuccess Callback
    // This method accepts a Position object, which contains the
    // current GPS coordinates
    //
    var onSuccess = function(position) {
        var element = document.getElementById('geolocation');
        element.innerHTML = 'Latitude: '+ position.coords.latitude         +'<br/>' +
               'Longitude: '            + position.coords.longitude        +<br/>' +
               'Altitude: '             + position.coords.altitude         +'<br/>' +
               'Accuracy: '             + position.coords.accuracy         +<br/>' +
               'Altitude Accuracy: '    + position.coords.altitudeAccuracy +'<br/>' +
               'Heading: '              + position.coords.heading          +<br/>' +
                'timestamp: '            + position.timestamp              +<br/>';
    };

    // onError Callback receives a PositionError object
    //
    function onError(error) {
        alert('code: '    + error.code    + '\n' +
              'message: ' + error.message + '\n');
    }

    navigator.geolocation.getCurrentPosition(onSuccess, onError);
Run Code Online (Sandbox Code Playgroud)

是否有可能(使用phonegap)在错误功能上打开对话框,这会引导我们进行位置设置(用户可以让我访问他的位置)而不是警报,因为它是在google maps android应用程序中完成的(截图如下) ? 像这样

ant*_*oid 0

我会按照你所说的去做,创建对话框,然后将它们发送到设置;我假设您已设法在适当的时间调用 onError fcn,那么那么

AlertDialog.Builder builder = new AlertDialog.Builder(context);
    builder.setTitle(getString(R.string.loc_man));
    builder.setMessage(getString(R.string.ask_for_gps));
    builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which)
            {
                Intent i = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                startActivity(i);       
            }
        });
    builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which)
            {
                Toast.makeText(getBaseContext(), getString(R.string.gps_no), Toast.LENGTH_SHORT).show();
                finish();
            }
        });
    builder.create().show();
Run Code Online (Sandbox Code Playgroud)

你还需要做的是从你的 javascript 调用这个函数...哦,这很有趣,b/c 你将同时使用很多非常酷的 java 概念,而我只使用过 Cordova,但是这应该都是一样的 =] 请记住,如果您在我的代码中看到某些未定义的变量,您可能应该假设它是一个字段。

假设您确定此代码出错,让我们编写一个接口名称;“Android”是一个非常合乎逻辑的名字

function onError(error) {
    alert('code: '    + error.code    + '\n' +
          'message: ' + error.message + '\n');
    Android.TurnOnTuneIn();
}
Run Code Online (Sandbox Code Playgroud)

现在回到你的Java,在你的phonegap应用程序中grep以查找它具有“WebView”的位置;如果它像我的 cordova 实现一样,它会在某个地方有 webview.loadUrl() 。打开定义该类的文件;这是编辑/放置我们在这个问题中正在处理的所有java的一个。在“public class PhoneGapActivity extends Activity”之类的内容之后,插入“implements CordovaInterface”(我认为不是 PhoneGapInterface );如果您的 IDE 在实现抽象方法的选项中出现错误,请点击该错误。

确保WebView是类中的字段,而不是方法中的变量,然后

    //CordovaWebView should work, but maybe it needs to be PhoneGapWebView, you're smart, you'll figure it out =]
            webView = (CordovaWebView) findViewById(R.id.data_window);
    webView.getSettings().setJavaScriptEnabled(true);
    webView.getSettings().setBuiltInZoomControls(false);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED, WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED); //this always seemed like a good idea to me
    webView.addJavascriptInterface(new JSInterface(this), "Android"); //see the interface name? =]
//this line should already be in this class, just re-use it
webView.loadUrl("file:///"+getContext().getFilesDir().toString()+"/index.html");
Run Code Online (Sandbox Code Playgroud)

现在制作该界面:

public class JSInterface {
    // these fcns are exposed to the WebView 
    private Context context;
    public JSInterface(Context context)
    {
        context = context;
    }
    @JavascriptInterface
    public void doEchoTest(String echo)
    {
//A useful test; I usually use it in a webViewClient that runs the function that calls this in my javascript with this:
//webView.loadUrl("javascript:echo('"echo!!!"');"); //this exact formatting
//but webViewClient is outside the scope of your question and would just confuse the 
//issue; however, you may need to implement 
//webViewClient with an delaying asynctask to seperatly run the js you loaded with the webpage,
//again, I used to do this ground-up, and phoneGap Might Just Work.

        Toast.makeText(context, echo, Toast.LENGTH_SHORT).show();   
    }
    @JavascriptInterface
    public void TurnOnTuneIn
    {
        aMethodThatHasThatFirstBitOfCodeIPublished();
    }
}
Run Code Online (Sandbox Code Playgroud)

我喜欢界面=]

其余的都是适合您的目的的样板文件(但是玩起来很有趣!)并且您可能不需要太多(如果有的话)。如果您注意到我放在顶部的方法没有按照您想要的方式返回,您可以使用 startActivityForResult 方法来执行相同的操作,我敢打赌它会很好地工作;注意“超级”。调用 Override 所做的操作;您只需要意图(就像我在顶部向您展示的那样)和一些参考号来接收结果......再次,超出了问题的范围。另外,我还提供了对与我一起使用它的 ResultCallback b/ca 人员的支持,但我自己不使用它。

@Override
public Activity getActivity(){
    return this;
}

@Override
public void setActivityResultCallback(CordovaPlugin plugin) {
    this.activityResultCallback = plugin;
}

public void startActivityForResult(CordovaPlugin command, Intent intent, int requestCode) {
    this.activityResultCallback = command;
    this.activityResultKeepRunning = this.keepRunning;

// If multitasking turned on, then disable it for activities that return results
    if (command != null) {
        this.keepRunning = false;
    }

// Start activity
    super.startActivityForResult(intent, requestCode);
}

@Override
public void cancelLoadUrl(){
//  no op
}

@Override
public Object onMessage(String id, Object data) {
        LOG.d("is", "onMessage(" + id + "," + data + ")");
        if ("exit".equals(id)) {
            super.finish();
        }
        return null;
}
@Override 
public void onPause() {
    Method pause = null; // Pauses the webview. 
    try { 
        pause = WebView.class.getMethod("onPause"); 
    } 
    catch (SecurityException e) { } 
    catch (NoSuchMethodException e) { } 
    if (pause != null) {
        try { pause.invoke(webView); 
        } 
        catch (InvocationTargetException e) { } 
        catch (IllegalAccessException e) { } 
    } 
    else { 
    // No such method. Stores the current URL. 
        suspendUrl = webView.getUrl(); // And loads a URL without any processing. 
        webView.loadUrl("file:///android_asset/nothing.html"); 
    } 
    super.onPause(); 
}

@Override 
public void onResume() { 
    super.onResume(); 
    Method resume = null; // Resumes the webview. 
    try { 
        resume = WebView.class.getMethod("onResume"); 
    } 
    catch (SecurityException e) { } 
    catch (NoSuchMethodException e) { } 
    if (resume != null) { 
        try { 
            resume.invoke(webView); 
        } 
        catch (InvocationTargetException e) { } 
        catch (IllegalAccessException e) { } 
    } 
    else if (webView != null) { // No such method. Restores the suspended URL. 
        if (suspendUrl == null) { 
            //this should be wherever you have your page; you can probably copy it from what is there now.
webView.loadUrl("file:///"+getContext().getFilesDir().toString()+"/index.html");
        } 
        else { 
            webView.loadUrl(suspendUrl); 
        } 
    }
}
Run Code Online (Sandbox Code Playgroud)

希望这能让你走得更远;如果您还没有使用它,请记住使用版本控制,这样您就可以肆无忌惮地进行编辑!

赫夫