Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/232.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 无法获取用户在intentservice中的当前位置_Android_Dictionary_Location_Intentservice - Fatal编程技术网

Android 无法获取用户在intentservice中的当前位置

Android 无法获取用户在intentservice中的当前位置,android,dictionary,location,intentservice,Android,Dictionary,Location,Intentservice,我想将用户的当前位置发布到我的php后端应用程序API中。我正在使用一个在后台运行的intent服务,在我的intent服务中获取位置时出现问题 请查看下面的代码 public class SampleSchedulingService extends IntentService implements LocationListener{ JSONParser jsonParser; public static final String URL_LOCATION = Constant.APP_

我想将用户的当前位置发布到我的php后端应用程序API中。我正在使用一个在后台运行的intent服务,在我的intent服务中获取位置时出现问题

请查看下面的代码

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

}

您需要在某个时候请求位置更新:

 // 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);

如何在intent服务中获取我当前的lat长度?一旦您请求一个location onLocationChanged将被调用,并将在代码中为您提供一个location对象arg0。然后,您可以调用arg0.getLatitude和arg0.getLongitudenow异常正在向死线程上的处理程序发送消息