gpt4 book ai didi

java - 当我将它传递给 asyncTask 时,Android Location 对象返回 null

转载 作者:行者123 更新时间:2023-11-29 20:45:51 25 4
gpt4 key购买 nike

我将 android 用户位置纬度和经度连同 registration ID 和其他参数作为 Asynctask( Activity 的嵌套类)中的 json 对象发送到服务器。但是 Location 对象(在应用程序开始时具有值)在 Activity 中实例化了

location = LocationServices.FusedLocationApi
.getLastLocation(mgoogleapiclient);

在 Asynctask 类中返回 null。有人可以向我解释为什么吗?我是否必须使用单独的类来获取用户位置并将其发送到另一个异步任务或服务(从架构的角度来看这没有意义)?

Location mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);
if (mLastLocation != null) {
PostData pdata = new PostData();
double latitude = mLastLocation.getLatitude();
double longitude = mLastLocation.getLongitude();
pdata.execute(String.valueOf(latitude), String.valueOf(longitude));
}

我正在从 AsyncTask 类中检索它:

json.put("latitude", String.valueOf(args[1]));
json.put("longitude", String.valueOf(args[2]));

但是当我调试它时,我得到了从另一个方法发送到 AsyncTask 类的注册 ID。我希望我说清楚了。

@Override
protected String doInBackground(String... args) {
try {
try {
URL url;
HttpURLConnection urlConn;
url = new URL ("myphp.php");
urlConn = (HttpURLConnection)url.openConnection();
urlConn.setDoInput (true);
urlConn.setDoOutput (true);
urlConn.setUseCaches (false);
urlConn.setRequestProperty("Content-Type","application/json");
urlConn.setRequestProperty("Accept", "application/json");
urlConn.setChunkedStreamingMode(0);
urlConn.setRequestMethod("POST");
urlConn.connect();
//get google account
AccountManager am = AccountManager.get(getBaseContext()); // "this" references the current Context
Account[] accounts = am.getAccountsByType("com.google");

//Create JSONObject here
JSONObject json = new JSONObject();
json.put("regID", String.valueOf(args[0]));
json.put("Google account", accounts[0].name);
json.put("name", "Amanda");
json.put("tel", "2069994444");
json.put("latitude", String.valueOf(args[1]));
json.put("longitude", String.valueOf(args[2]));

String postData=json.toString();

// Send POST output.
OutputStreamWriter os = new OutputStreamWriter(urlConn.getOutputStream(), "UTF-8");
os.write(postData);
Log.i("NOTIFICATION", "Data Sent");
os.close();

BufferedReader reader = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
String msg="";
String line = "";
while ((line = reader.readLine()) != null) {
msg += line; }
Log.i("msg=",""+msg);
} catch (MalformedURLException muex) {
// TODO Auto-generated catch block
muex.printStackTrace();
} catch (IOException ioex){
ioex.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
Log.e("ERROR", "There is error in this code");

}
return null;

}

下面是我发送注册ID的方式

gcm = GoogleCloudMessaging.getInstance(this);
regid = getRegistrationId(context);
if (!regid.isEmpty()) {
PostData pd = new PostData();
pd.execute(regid);
} else {
//register
registerInBackground();
}

最佳答案

问题是您在不同的时间向 AsyncTask 发送了两组不同的 varargs

当您调用 execute() 时,您应该将所有必要的数据发送到 AsyncTask,以便它获得所需的数据。

因此,您需要准备好所有数据,并在一次调用中将其发送到 execute(),如下所示:

Location mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);

gcm = GoogleCloudMessaging.getInstance(this);
regid = getRegistrationId(context);
if (!regid.isEmpty() && mLastLocation != null) {
double latitude = mLastLocation.getLatitude();
double longitude = mLastLocation.getLongitude();
PostData pd = new PostData();
pd.execute(regid, String.valueOf(latitude), String.valueOf(longitude));
} else {
//register if regid is empty
if (regid.isEmpty()){
registerInBackground();
}
}

此外,无需对传递给 doInBackground() 的字符串参数调用 String.valueOf(),因此您可以删除这些调用:

@Override
protected String doInBackground(String... args) {
try {
try {
URL url;
HttpURLConnection urlConn;
url = new URL ("myphp.php");
urlConn = (HttpURLConnection)url.openConnection();
urlConn.setDoInput (true);
urlConn.setDoOutput (true);
urlConn.setUseCaches (false);
urlConn.setRequestProperty("Content-Type","application/json");
urlConn.setRequestProperty("Accept", "application/json");
urlConn.setChunkedStreamingMode(0);
urlConn.setRequestMethod("POST");
urlConn.connect();
//get google account
AccountManager am = AccountManager.get(getBaseContext()); // "this" references the current Context
Account[] accounts = am.getAccountsByType("com.google");

//Create JSONObject here
JSONObject json = new JSONObject();
json.put("regID", args[0]); //modified
json.put("Google account", accounts[0].name);
json.put("name", "Amanda");
json.put("tel", "2069994444");
json.put("latitude", args[1]); //modified
json.put("longitude", args[2]); //modified

String postData=json.toString();

// Send POST output.
OutputStreamWriter os = new OutputStreamWriter(urlConn.getOutputStream(), "UTF-8");
os.write(postData);
Log.i("NOTIFICATION", "Data Sent");
os.close();

BufferedReader reader = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
String msg="";
String line = "";
while ((line = reader.readLine()) != null) {
msg += line; }
Log.i("msg=",""+msg);
} catch (MalformedURLException muex) {
// TODO Auto-generated catch block
muex.printStackTrace();
} catch (IOException ioex){
ioex.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
Log.e("ERROR", "There is error in this code");

}
return null;

}

编辑:听起来您应该注册一个位置监听器以便明确请求位置。以下是示例代码,您可以将其用作引用,以便在您的代码中注册位置监听器:

public class MainActivity extends Activity implements
GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {

LocationRequest mLocationRequest;
GoogleApiClient mGoogleApiClient;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

buildGoogleApiClient();
mGoogleApiClient.connect();
}

@Override
protected void onPause(){
super.onPause();
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
}

protected synchronized void buildGoogleApiClient() {
Toast.makeText(this,"buildGoogleApiClient",Toast.LENGTH_SHORT).show();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}

@Override
public void onConnected(Bundle bundle) {
Toast.makeText(this,"onConnected",Toast.LENGTH_SHORT).show();

mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(10);
mLocationRequest.setFastestInterval(10);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
//mLocationRequest.setPriority(LocationRequest.PRIORITY_LOW_POWER);
//mLocationRequest.setSmallestDisplacement(0.1F);

LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}

@Override
public void onConnectionSuspended(int i) {
Toast.makeText(this,"onConnectionSuspended",Toast.LENGTH_SHORT).show();
}

@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Toast.makeText(this,"onConnectionFailed",Toast.LENGTH_SHORT).show();
}

@Override
public void onLocationChanged(Location location) {

Log.d("locationtesting", "accuracy: " + location.getAccuracy() + " lat: " + location.getLatitude() + " lon: " + location.getLongitude());

Toast.makeText(this,"Location Changed",Toast.LENGTH_SHORT).show();


//unregister here if you only need one location update:
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
}
}

关于java - 当我将它传递给 asyncTask 时,Android Location 对象返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30384803/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com