Android 位置管理器不起作用

Posted

技术标签:

【中文标题】Android 位置管理器不起作用【英文标题】:Android location manager doesn't work 【发布时间】:2013-01-01 22:45:26 【问题描述】:

我正在尝试创建和显示设备当前位置和定义点之间的路线。 我使用此代码:

public class RoutePath extends MapActivity 
    /** Called when the activity is first created. */
    MapView mapView;
    private RoutePath _activity;
    GeoPoint srcGeoPoint,destGeoPoint;
    private static List<Overlay> mOverlays;
    MapController mc;
    Location location;
    private MyLocationOverlay myLocationOverlay;
    String n;
    double longitude;
    double latitude;


    @Override
    public void onCreate(Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        SharedData data = SharedData.getInstance();
        mapView = new MapView(this,"apyKey");
        mapView.setClickable(true); 




        setContentView(mapView);
        _activity = this;
        LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE); 
        Location location =lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
        longitude = location.getLongitude();
        latitude = location.getLatitude();

        double src_lat = latitude;
        double src_long = longitude;
        double dest_lat = 38.1267303;
        double dest_long = 13.3466097;

       String n = String.valueOf(src_long);
       Log.d("asd",n);

        if(src_lat == -1 || src_long == -1 || dest_lat == -1 || dest_long == -1)
            showAlert("Please enter source and destination points");
        else

            srcGeoPoint = new GeoPoint((int) (src_lat * 1E6),(int) (src_long * 1E6));
            destGeoPoint = new GeoPoint((int) (dest_lat * 1E6),(int) (dest_long * 1E6));

            List<Overlay> mapOverlays = mapView.getOverlays();
            Drawable srcdrawable = this.getResources().getDrawable(R.drawable.pushpin1);
            CustomItemizedOverlay srcitemizedOverlay = new CustomItemizedOverlay(srcdrawable);
            //CustomItemizedOverlay srcitemizedOverlay = new CustomItemizedOverlay(getDrawable("com/agarwal/route/pin_green.png"));
            OverlayItem srcoverlayitem = new OverlayItem(srcGeoPoint, "Hello!", "This is your Location.");

            Drawable destdrawable = this.getResources().getDrawable(R.drawable.pushpin1);
            CustomItemizedOverlay  destitemizedOverlay = new CustomItemizedOverlay( destdrawable );
           // CustomItemizedOverlay destitemizedOverlay = new CustomItemizedOverlay(getDrawable("com/agarwal/route/pin_red.png"));
            OverlayItem destoverlayitem = new OverlayItem(destGeoPoint, "Hello!", "This is dest Location.");

            srcitemizedOverlay.addOverlay(srcoverlayitem);
            destitemizedOverlay.addOverlay(destoverlayitem);

            mapOverlays.add(srcitemizedOverlay);
            mapOverlays.add(destitemizedOverlay);

            connectAsyncTask _connectAsyncTask = new connectAsyncTask();
            _connectAsyncTask.execute();       
            mapView.setBuiltInZoomControls(true);
            mapView.displayZoomControls(true);
            mOverlays = mapView.getOverlays();
            mapView.getController().animateTo(srcGeoPoint);
            mapView.getController().setZoom(12);
        
    
    @Override
    protected boolean isRouteDisplayed() 
        // TODO Auto-generated method stub
        return false;
    
    //era private prima di 
   private class connectAsyncTask extends AsyncTask<Void, Void, Void>
        private ProgressDialog progressDialog;
        @Override
        protected void onPreExecute() 
            // TODO Auto-generated method stub
            super.onPreExecute();

            progressDialog = new ProgressDialog(_activity);
            progressDialog.setMessage("Caricamento del percorso...");
            progressDialog.setIndeterminate(true);
            progressDialog.show();
        
        @Override
        protected Void doInBackground(Void... params) 
            // TODO Auto-generated method stub
            fetchData();

            return null;
        
        @Override
        protected void onPostExecute(Void result) 
            // TODO Auto-generated method stub
            super.onPostExecute(result);           
            if(doc!=null)
                Overlay ol = new MyOverlay(_activity,srcGeoPoint,srcGeoPoint,1);
                mOverlays.add(ol);
                NodeList _nodelist = doc.getElementsByTagName("status");
                Node node1 = _nodelist.item(0);
                String _status1  = node1.getChildNodes().item(0).getNodeValue();
                if(_status1.equalsIgnoreCase("OK"))
                    NodeList _nodelist_path = doc.getElementsByTagName("overview_polyline");
                    Node node_path = _nodelist_path.item(0);
                    Element _status_path = (Element)node_path;
                    NodeList _nodelist_destination_path = _status_path.getElementsByTagName("points");
                    Node _nodelist_dest = _nodelist_destination_path.item(0);
                    String _path  = _nodelist_dest.getChildNodes().item(0).getNodeValue();
                    List<GeoPoint> _geopoints = decodePoly(_path);
                    GeoPoint gp1;
                    GeoPoint gp2;
                    gp2 = _geopoints.get(0);
                    Log.d("_geopoints","::"+_geopoints.size());
                    for(int i=1;i<_geopoints.size();i++) // the last one would be crash
                    

                        gp1 = gp2;
                        gp2 = _geopoints.get(i);
                        Overlay ol1 = new MyOverlay(gp1,gp2,2,Color.BLUE);
                        mOverlays.add(ol1);
                    
                    Overlay ol2 = new MyOverlay(_activity,destGeoPoint,destGeoPoint,3);
                    mOverlays.add(ol2);

                    progressDialog.dismiss();
                else
                    showAlert("Unable to find the route");
                

                Overlay ol2 = new MyOverlay(_activity,destGeoPoint,destGeoPoint,3);
                mOverlays.add(ol2);
                progressDialog.dismiss();
                mapView.scrollBy(-1,-1);
                mapView.scrollBy(1,1);
            else
                showAlert("Unable to find the route");
            

        

     //end Async
    Document doc = null;
    private void fetchData()
    

        StringBuilder urlString = new StringBuilder();
        urlString.append("http://maps.google.com/maps/api/directions/xml?origin=");
        urlString.append( Double.toString((double)srcGeoPoint.getLatitudeE6()/1.0E6 ));
        urlString.append(",");
        urlString.append( Double.toString((double)srcGeoPoint.getLongitudeE6()/1.0E6 ));
        urlString.append("&destination=");//to
        urlString.append( Double.toString((double)destGeoPoint.getLatitudeE6()/1.0E6 ));
        urlString.append(",");
        urlString.append( Double.toString((double)destGeoPoint.getLongitudeE6()/1.0E6 ));
        urlString.append("&sensor=true&mode=driving");    
        Log.d("url","::"+urlString.toString());
        HttpURLConnection urlConnection= null;
        URL url = null;
        try
        
            url = new URL(urlString.toString());
            urlConnection=(HttpURLConnection)url.openConnection();
            urlConnection.setRequestMethod("GET");
            urlConnection.setDoOutput(true);
            urlConnection.setDoInput(true);
            urlConnection.connect();
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            doc = (Document) db.parse(urlConnection.getInputStream());//Util.XMLfromString(response);
        catch (MalformedURLException e)
            e.printStackTrace();
        catch (IOException e)
            e.printStackTrace();
        catch (ParserConfigurationException e)
            e.printStackTrace();
        
        catch (SAXException e) 
            // TODO Auto-generated catch block
            e.printStackTrace();
        
    
    private List<GeoPoint> decodePoly(String encoded) 

        List<GeoPoint> poly = new ArrayList<GeoPoint>();
        int index = 0, len = encoded.length();
        int lat = 0, lng = 0;

        while (index < len) 
            int b, shift = 0, result = 0;
            do 
                b = encoded.charAt(index++) - 63;
                result |= (b & 0x1f) << shift;
                shift += 5;
             while (b >= 0x20);
            int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
            lat += dlat;

            shift = 0;
            result = 0;
            do 
                b = encoded.charAt(index++) - 63;
                result |= (b & 0x1f) << shift;
                shift += 5;
             while (b >= 0x20);
            int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
            lng += dlng;

            GeoPoint p = new GeoPoint((int) (((double) lat / 1E5) * 1E6),
                    (int) (((double) lng / 1E5) * 1E6));
            poly.add(p);
        

        return poly;
    
    private void showAlert(String message)
        AlertDialog.Builder alert = new AlertDialog.Builder(_activity);
        alert.setTitle("Error");
        alert.setCancelable(false);
        alert.setMessage(message);
        alert.setPositiveButton("Ok",new DialogInterface.OnClickListener() 
            public void onClick(DialogInterface dialog, int which) 
                // TODO Auto-generated method stub

            
        );
        alert.show();
    


    private Drawable getDrawable(String fileName)
        return Drawable.createFromStream(_activity.getClass().getClassLoader().getResourceAsStream(fileName), "pin");
    



这是针对智能手机 Galaxy Nexus,android 4.2 的应用程序。 我在我的平板电脑 android 4.0.2 上对其进行了测试,它运行良好。 但是当我在智能手机上测试它时,它崩溃了。 我试图用LocationManager.GPS_PROVIDER 更改LocationManager.NETWORK_PROVIDER,但它还是崩溃了。我无法解决这个问题。谁能帮帮我?

【问题讨论】:

LogCat 中的任何错误跟踪? “不起作用”并没有告诉我们出了什么问题,请发布堆栈跟踪。 为什么你处理这么多不同的catch 案件,而你却以同样的方式处理它们? 我直接在设备上测试。当我用模拟器测试它时,LogCat 说纬度和经度为空 【参考方案1】:

我为同样的问题苦苦挣扎了好几个小时。同一段代码在我的 Android 2.7 设备上运行良好,但不适用于我的 Android 4.1.1。最终,我发现,由于某些原因,如果没有先调用 requestLocationUpdates(),则 getLastKnownLocation() 不起作用。 结果,我的 LocationListener 在我放了这两行之后开始更新:

locationManager.requestLocationUpdates(provider, 1000, 10, locationListener);
Location location = locationManager.getLastKnownLocation(provider);

希望对你有帮助。

【讨论】:

【参考方案2】:

您是否在清单文件中授予了适当的权限

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>

查看 Android 开发文档here

【讨论】:

在清单中有文档中指示的所有权限【参考方案3】:

你得到一个空指针的机会。

您从 getLastKnownLocation() 获取位置,然后使用此对象而不检查它是否为空。如果没有已知位置,getLastKnownLocation 可以返回 null。

【讨论】:

以上是关于Android 位置管理器不起作用的主要内容,如果未能解决你的问题,请参考以下文章

CAD2014安全系统软件锁许可管理器不起作用或未正确安装

所选项目上的 Android 微调器不起作用?

将打印目录功能添加到 Windows 资源管理器不起作用

ansi-terminal 和本机 io 管理器不起作用

应用程序关闭时,带有广播接收器的工作管理器不起作用

包含的 php 文件中的 jQuery 选择器不起作用