【问题标题】:Open Android Location Settings using phonegap使用 phonegap 打开 Android 位置设置
【发布时间】:2014-04-07 05:58:04
【问题描述】:

我通过 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);

是否有可能(使用phonegap)在错误功能上打开对话框,这将引导我们进入位置设置(用户可以让我访问他的位置)而不是警报,就像在谷歌地图android应用程序中所做的那样(下面的截图)?

【问题讨论】:

标签: android cordova geolocation phonegap-plugins


【解决方案1】:

我与你分享这个 phonegap 插件,它可以让你做到这一点。我作为贡献者将该功能添加到该插件中。 https://github.com/BastienL/GPSDetector

【讨论】:

    【解决方案2】:

    我会照你说的做,创建对话框,然后将它们发送到设置;我假设您已经设法在适当的时候调用了 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();
    

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

    假设你确定这段代码会出错,让我们组成一个接口名称; “Android”是一个非常合乎逻辑的产品

    function onError(error) {
        alert('code: '    + error.code    + '\n' +
              'message: ' + error.message + '\n');
        Android.TurnOnTuneIn();
    }
    

    现在回到您的 Java 中,在您的 phonegap 应用程序周围用 grep 查找它有“WebView”的位置;如果它像我的科尔多瓦实现一样,它会在某个地方有 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");
    

    现在制作那个界面:

    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();
        }
    }
    

    我喜欢界面 =]

    其余的对于您的目的来说是相当样板的(但玩起来很有趣!),如果有的话,您可能不需要太多。如果你注意到我提出的方法没有返回你想要的方式,你可以使用 startActivityForResult 方法来做同样的事情,我敢打赌它会很好地工作;注意“超级”。调用 Override 进行;您只需要 Intent (就像我在顶部显示的那样)和一些参考号来接收结果......再次,超出了问题的范围。此外,我还加入了对 ResultCallback b/c 的支持,一个与我一起工作的人使用它,但我自己不使用它。

    @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); 
            } 
        }
    }
    

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

    gl 高频

    【讨论】:

    • 我根本不懂java,所以这只是我在phonegap上的第一步,我不知道如何处理你给我的代码,你能详细解释一下吗跨度>
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-09
    • 1970-01-01
    相关资源
    最近更新 更多