我一直在解決這個問題。使用LocationListener和HttpUrlConnection發佈數據在AsyncTask中的即時位置
我有一個AsyncTask,每20秒獲取用戶的網絡位置並將數據發佈到遠程服務器。
我已請求的權限,如圖屬於
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
這裏是MainActivitiy的OnCreate()和代碼
public class TraficMain extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
setContentView(R.layout.activity_main);
new UrlPositionAsynck().execute();
}
private class UrlPositionAsynck extends AsyncTask<Void, Void , String> {
public double longitude, latitude;
public URL url;
protected LocationManager locationManager;
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
@Override
protected String doInBackground(Void... urlink) {
GPSPosition gpsPosition = new GPSPosition(TraficMain.this);
locationManager=(LocationManager)getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 20000, 0, gpsPosition);
Position position = gpsPosition.getPosition();
String params= "lb_lo=" + position.getLb_longitude() + "&lb_la=" + position.getLb_latitude();
try {
url = new URL("http://myremote_url");
byte[] param=params.getBytes("UTF-8");
int postLength=param.length;
HttpURLConnection strConn = (HttpURLConnection) url.openConnection();
strConn.setDoOutput(true);
strConn.setInstanceFollowRedirects(false);
strConn.setRequestMethod("POST");
strConn.setConnectTimeout(60000);
strConn.setChunkedStreamingMode(0);
strConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
strConn.setRequestProperty("charset", "utf-8");
strConn.setRequestProperty("Content-Length", Integer.toString(postLength));
strConn.setUseCaches(false);
OutputStream out=strConn.getOutputStream();
BufferedWriter data =new BufferedWriter(new OutputStreamWriter(strConn.getOutputStream()));
data.write(params);
data.flush();
data.close();
out.flush();
out.close();
BufferedReader br = new BufferedReader(new InputStreamReader((strConn.getInputStream())));
StringBuilder sb = new StringBuilder();
String output;
while ((output = br.readLine()) != null) {
sb.append(output);
}
}catch(IOException io){
Log.i("Connection Problem :", io.getMessage());
}
return null;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
}
}
的其餘部分,我用這個類實現獲得位置LocationListener
public class GPSPosition implements LocationListener{
Activity myContext;
public double longitude, latitude;
public GPSPosition(Activity context){
this.myContext=context;
}
@Override
public void onLocationChanged(Location location) {
longitude = location.getLongitude();
latitude = location.getLatitude();
TextView txt = (TextView) this.myContext.findViewById(R.id.txtPosition);
txt.setText(longitude + ", " + latitude);
}
@Override
public void onProviderDisabled(String provider) {}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {}
@Override
public void onProviderEnabled(String provider) {}
public Position getPosition(){
return new Position(this.longitude, this.latitude);
}
我的代碼已經過問題。我只在應用程序啓動並且經度和緯度始終等於0時發佈數據。
我期待將數據發佈到遠程服務器,每20秒鐘一次。 有人可以告訴如何處理這個問題來解決嗎?我已經花了整個週末
編輯 這是onCreate()的新代碼。 即使設備更改位置,位置的值也不變,我不知道爲什麼會發生這種情況。
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
setContentView(R.layout.activity_main);
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
final GPSPosition gpsPosition = new GPSPosition(TraficMain.this);
locationManager=(LocationManager)getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, gpsPosition);
new UrlPositionAsynck().execute(gpsPosition.getPosition());
}
}, 20000);
}
private class UrlPositionAsynck extends AsyncTask<Position, Void , String> {
public double longitude, latitude;
public URL url;
protected LocationManager locationManager;
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
@Override
protected String doInBackground(Position... urlink) {
Position position = urlink[0];
String params= "lb_lo=" + position.getLb_longitude() + "&lb_la=" + position.getLb_latitude();
try {
url = new URL("http://remote_url");
byte[] param=params.getBytes("UTF-8");
int postLength=param.length;
HttpURLConnection strConn = (HttpURLConnection) url.openConnection();
strConn.setDoOutput(true);
strConn.setInstanceFollowRedirects(false);
strConn.setRequestMethod("POST");
strConn.setConnectTimeout(60000);
strConn.setChunkedStreamingMode(0);
strConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
strConn.setRequestProperty("charset", "utf-8");
strConn.setRequestProperty("Content-Length", Integer.toString(postLength));
strConn.setUseCaches(false);
OutputStream out=strConn.getOutputStream();
BufferedWriter data =new BufferedWriter(new OutputStreamWriter(strConn.getOutputStream()));
data.write(params);
data.flush();
data.close();
out.flush();
out.close();
BufferedReader br = new BufferedReader(new InputStreamReader((strConn.getInputStream())));
StringBuilder sb = new StringBuilder();
String output;
while ((output = br.readLine()) != null) {
sb.append(output);
}
}catch(IOException io){
io.printStackTrace();
}
return null;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
}
東西那麼你正在執行一次你的AsyncTask每20秒後運行它。 –
你的意思是我應該在doInBackGround裏添加一個while循環嗎? –