2015-01-15 36 views
1

我想將用戶的當前位置發佈到我的php後端應用程序(API)中。我正在使用在後臺運行的意向服務,在我的意向服務中獲取位置時出現問題。無法在intentservice中獲取用戶當前位置

請低於

public class SampleSchedulingService extends IntentService implements LocationListener{ 

JSONParser jsonParser; 
public static final String URL_LOCATION = Constant.APP_URL_LOCATION; 

ConnectionDetector cd; 
AlertDialogManager alert = new AlertDialogManager(); 

public SampleSchedulingService() { 
    super("SchedulingService"); 
} 

public static final String TAG = "Scheduling Demo"; 
public static final String SEARCH_STRING = "doodle"; 
public static final String URL = "http://www.google.com"; 
private NotificationManager mNotificationManager; 
NotificationCompat.Builder builder; 

@Override 
protected void onHandleIntent(Intent intent) { 
    // The URL from which to fetch content. 
    String urlString = URL; 

    String result =""; 

    jsonParser = new JSONParser(getApplicationContext()); 

    try { 
     if(isNetworkAvailable()){ 
      result = loadFromNetwork(urlString); 
     } 
    } catch (IOException e) { 
     Log.i(TAG, "connection error"); 
    } 

    if (result.indexOf(SEARCH_STRING) != -1) { 
     Log.i(TAG, "Found"); 
    } else { 
     Log.i(TAG, "Not found. :-("); 
    } 
    // Release the wake lock provided by the BroadcastReceiver. 
    SampleAlarmReceiver.completeWakefulIntent(intent); 
    // END_INCLUDE(service_onhandle) 
} 


/** Given a URL string, initiate a fetch operation. */ 
private String loadFromNetwork(String urlString) throws IOException { 
    InputStream stream = null; 
    String str =""; 

    try { 
     stream = downloadUrl(urlString); 
     str = readIt(stream); 
    } finally { 
     if (stream != null) { 
      stream.close(); 
     }  
    } 
    return str; 
} 

/** 
* Given a string representation of a URL, sets up a connection and gets 
* an input stream. 
* @param urlString A string representation of a URL. 
* @return An InputStream retrieved from a successful HttpURLConnection. 
* @throws IOException 
*/ 
private InputStream downloadUrl(String urlString) throws IOException { 

    // Building Parameters 
    List<NameValuePair> params = new ArrayList<NameValuePair>(); 
    PlacesFragment latlng = new PlacesFragment(); 
    double[] latlong = latlng.getLocation(); 
    params.add(new BasicNameValuePair("lat", latlong[0]+"")); 
    params.add(new BasicNameValuePair("lng", latlong[1]+"")); 

    JSONObject json = jsonParser.makeHttpRequest(URL_LOCATION, "POST", params); 

    URL url = new URL(urlString); 
    HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 
    conn.setReadTimeout(10000 /* milliseconds */); 
    conn.setConnectTimeout(15000 /* milliseconds */); 
    conn.setRequestMethod("POST"); 
    conn.setRequestProperty("Content-Type", "application/json"); 
    conn.setRequestProperty("Accept", "application/json"); 
    conn.setDoInput(true); 
    conn.setDoOutput(true); 
    OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); 
    wr.write(json.toString()); 
    wr.flush(); 
    StringBuilder sb = new StringBuilder(); 
    int httpResult = conn.getResponseCode(); 
    if(httpResult ==HttpURLConnection.HTTP_OK){ 

     BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(),"utf-8")); 

     String line = null; 

     while ((line = br.readLine()) != null) { 
     sb.append(line + "\n"); 
     } 

     br.close(); 

     System.out.println(""+sb.toString()); 

    }else{ 
     System.out.println(conn.getResponseMessage()); 
    } 
    // Start the query 
    conn.connect(); 
    InputStream stream = conn.getInputStream(); 
    return stream; 
} 

/** 
* Reads an InputStream and converts it to a String. 
* @param stream InputStream containing HTML from www.google.com. 
* @return String version of InputStream. 
* @throws IOException 
*/ 
private String readIt(InputStream stream) throws IOException { 

    StringBuilder builder = new StringBuilder(); 
    BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); 
    for(String line = reader.readLine(); line != null; line = reader.readLine()) 
     builder.append(line); 
    reader.close(); 
    return builder.toString(); 
} 

@Override 
public void onLocationChanged(Location arg0) { 
    // TODO Auto-generated method stub 

} 
private boolean isNetworkAvailable() { 
    ConnectivityManager connectivityManager 
      = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); 
    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo(); 
    return activeNetworkInfo != null && activeNetworkInfo.isConnected(); 
} 

}

回答

0

上的代碼來看看你需要在某一時刻要求位置更新:

// Acquire a reference to the system Location Manager 
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE); 

// Register the listener with the Location Manager to receive location updates 
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this); 

http://developer.android.com/guide/topics/location/strategies.html

+0

如何讓我的目前拉特在意向服務? –

+0

一旦你請求一個locationLocationChanged將被調用,並會在你的代碼中給你一個Location對象arg0。那麼你可以調用arg0.getLatitude()和arg0.getLongitude() –

+0

現在拋出一個異常「將消息發送給死亡線程上的處理程序」 –