如何将GPS位置值传递给android中的其他类?
问题描述:
我使用类来获得纬度和经度值,经过检查我确认数据是正确的,但我面临的问题是如何将值传递给其他函数并将其发送到PHP脚本,所以我可以存储值。这两个功能都属于同一类。以下是我的获取位置类代码。如何将GPS位置值传递给android中的其他类?
从这里我得到的GPS价值。
public void get_location(){
// Acquire a reference to the system Location Manager
LocationManager locationManager = (LocationManager) LoginActivity.this.getSystemService(Context.LOCATION_SERVICE);
// Define a listener that responds to location updates
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider.
String lat = Double.toString(location.getLatitude());
String lon = Double.toString(location.getLongitude());
}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
// Register the listener with the Location Manager to receive location updates
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
}
我需要将值传递给此函数,以便它可以发送到服务器。
public class SendPostRequest extends AsyncTask<String, Void, String> {
protected void onPreExecute(){}
protected String doInBackground(String... arg0) {
try {
URL url = new URL("http://localhost.com/save.php");
JSONObject postDataParams = new JSONObject();
postDataParams.put("lat", lat);
postDataParams.put("lon", lon);
Log.e("params",postDataParams.toString());
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(postDataParams));
writer.flush();
writer.close();
os.close();
int responseCode=conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
BufferedReader in=new BufferedReader(new
InputStreamReader(
conn.getInputStream()));
StringBuffer sb = new StringBuffer("");
String line="";
while((line = in.readLine()) != null) {
sb.append(line);
break;
}
in.close();
return sb.toString();
}
else {
return new String("false : "+responseCode);
}
}
catch(Exception e){
return new String("Exception: " + e.getMessage());
}
}
@Override
protected void onPostExecute(String result) {
Toast.makeText(getApplicationContext(), result,
Toast.LENGTH_LONG).show();
}
}
public String getPostDataString(JSONObject params) throws Exception {
StringBuilder result = new StringBuilder();
boolean first = true;
Iterator<String> itr = params.keys();
while(itr.hasNext()){
String key= itr.next();
Object value = params.get(key);
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(key, "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(value.toString(), "UTF-8"));
}
return result.toString();
}
这里是我执行ASYN任务
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new SendPostRequest().execute();
}
答
创建全球Double
数组(非常基本的):
static Double[] arr;
在你onCreate
:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new SendPostRequest().execute(arr); //changes made here
}
你get_location
方法:
public void get_location(){
// Acquire a reference to the system Location Manager
LocationManager locationManager = (LocationManager) LoginActivity.this.getSystemService(Context.LOCATION_SERVICE);
// Define a listener that responds to location updates
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider.
// getting location of user, don't parse to string latlng has to double
double lat = location.getLatitude();
double lon = location.getLongitude();
arr[0] = lat; //changes made here
arr[1] = lon; //changes made here
}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
// Register the listener with the Location Manager to receive location updates
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
}
传递价值Asynctask
:
public class SendPostRequest extends AsyncTask<Double, Void, String> {
protected void onPreExecute(){}
protected String doInBackground(Double arr) {
try {
URL url = new URL("http://localhost.com/save.php");
JSONObject postDataParams = new JSONObject();
postDataParams.put("lat", arr[0]); //changes made here
postDataParams.put("lon", arr[1]); //changes made here
Log.e("params",postDataParams.toString());
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(postDataParams));
writer.flush();
writer.close();
os.close();
int responseCode=conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
BufferedReader in=new BufferedReader(new
InputStreamReader(
conn.getInputStream()));
StringBuffer sb = new StringBuffer("");
String line="";
while((line = in.readLine()) != null) {
sb.append(line);
break;
}
in.close();
return sb.toString();
}
else {
return new String("false : "+responseCode);
}
}
catch(Exception e){
return new String("Exception: " + e.getMessage());
}
}
@Override
protected void onPostExecute(String result) {
Toast.makeText(getApplicationContext(), result,
Toast.LENGTH_LONG).show();
}
}
public String getPostDataString(JSONObject params) throws Exception {
StringBuilder result = new StringBuilder();
boolean first = true;
Iterator<String> itr = params.keys();
while(itr.hasNext()){
String key= itr.next();
Object value = params.get(key);
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(key, "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(value.toString(), "UTF-8"));
}
return result.toString();
}
答
只要改变你的代码的这部分功能:
public class SendPostRequest extends AsyncTask<Double, Void, String> {
protected void onPreExecute(){}
protected String doInBackground(Double... arg0) {
try {
URL url = new URL("http://localhost.com/save.php");
JSONObject postDataParams = new JSONObject();
postDataParams.put("lat", args[0]);
postDataParams.put("lon", args[1]);
和执行的AsyncTask:
new SendPostRequest().execute(lat,lon);
不要ü想通过LAT,L ng到下一个活动或需要传递给'Asynctask' – W4R10CK
嗨,传递拉特,lng到Asyntask – masterhunter
你在哪里执行'Asynctask'?它在getlocation()里面吗? – W4R10CK