2015-05-31 16 views
0

之後我嘗試在Android設備上獲得位置的代碼如下:我想在Android設備上獲得的位置,但它崩潰執行

private void openLocation() { 
    lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE); 
    Criteria c = new Criteria(); 
    pro = lm.getBestProvider(c,false); 
    Location l = lm.getLastKnownLocation(pro); 

    if (l != null) { 
     Toast.makeText(WebActivity.this, "Longitude : "+String.valueOf(l.getLongitude())+", Latitude : "+String.valueOf(l.getLatitude()), Toast.LENGTH_LONG).show(); 
    } else { 
     Toast.makeText(WebActivity.this,"loc object is null",Toast.LENGTH_LONG).show(); 
    } 

    mgac = new GoogleApiClient.Builder(this) 
      .addConnectionCallbacks(this) 
      .addOnConnectionFailedListener(this) 
      .addApi(LocationServices.API) 
      .build(); 
} 

,但在執行時會崩潰。代碼中出現了什麼問題,或者請給我一個工作代碼,給我定位字符串,並且我想使用get/post請求將數據發送到另一個url,並且此請求應該在後臺運行。

+0

如果它首先崩潰看到是它安慰控制檯中的一些錯誤/異常,如果是的是什麼? –

+0

使用LogCat檢查與您的崩潰相關的Java堆棧跟蹤:https://stackoverflow.com/questions/23353173/uncomfort-myapp-has-stopped-how-can-i-solve-this – CommonsWare

回答

0

這可能有助於U,

Thread thread = new Thread(new Runnable() { 
      @Override 
      public void run() { 

      try { 

       URL url = new URL(url); 
       HttpURLConnection conn = (HttpURLConnection) url 
         .openConnection(); 
       conn.setReadTimeout(10000 /* milliseconds */); 
       conn.setConnectTimeout(15000 /* milliseconds */); 
       conn.setRequestMethod("GET"); 
       conn.setDoInput(true); 
       // Starts the query 

       conn.connect(); 
       InputStream stream = conn.getInputStream(); 

       String data = convertStreamToString(stream); 

       // u can read data here 
       stream.close(); 


      } catch (Exception e) { 
      } 
     } 
    }); 

    thread.start(); 

&的convertStreamToString是,

static String convertStreamToString(java.io.InputStream is) { 
     java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A"); 
     return s.hasNext() ? s.next() : ""; 
    } 

這可以幫助你在後臺發送一些請求服務器,但 用於獲取位置我不非常確定。

+2

請解釋這是什麼這個問題。 – CommonsWare

+0

他想要使用get/post請求將這些數據發送到某個url,並且此請求應該在後臺運行,並且我認爲這是@Common先生的解決方案。 –

+0

@AkhileshKumar你是對的,但如果你能回答我的第一個問題 –

相關問題