无法在 intentservice 中获取用户当前位置
Unable to get users current location in intentservice
我想 post 用户的当前位置到我的 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);
http://developer.android.com/guide/topics/location/strategies.html
我想 post 用户的当前位置到我的 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);
http://developer.android.com/guide/topics/location/strategies.html