- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我将 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/
我正在尝试在 python 中编写正则表达式来查找目录路径:我的文本如下所示: text = "The public disk is: \\\\diskA\\FolderB\\SubFolderC\\
我想写一个LocationListener,它把最近最精确的位置作为它的位置。我打算在我的 LocationListener 中使用此代码: @Override public void
我想建立一个有光泽和 plotly 的交互式图表。 Shiny 有一个内置功能来获取有关用户交互的信息。比如:input$plot_click、input$plot_dblclick、input$pl
我正在使用 MobileFirst 提供的 WL.Device.Geo.acquirePosition(onGeoLocationSuccess, onGeoLocationFailure, opti
我最近开始使用 ionic 框架,它里面有 angular js。为了在屏幕之间导航,我使用了 $location.path 并且效果很好。但是,在我下载的一个示例中,我看到 $state.go 被用
谁能解释一下这种行为?我使用 history.pushState(null, null, '#test'); 推送历史状态。然后,当尝试使用console.log(window.location.ha
这里是相关代码: https://www.facebook.com/sharer/sharer.php?u={{$location.absUrl()}} https://www.facebook.c
这两个重定向之间有什么区别?我有一个应用程序,当我使用时,它可以在 chrome 和 android 4 上正常工作,但在 android 2.x.x 上不能正常工作 document.locatio
JavaScript 的区别是什么 window.location.href = window.location.href 和 window.location.reload() 功能? 最佳答案 如果
有什么区别 window.location.href="http://example.com"; window.location.replace("http://example.com"); wind
JavaScript 的区别是什么 window.location.href = window.location.href 和 window.location.reload() 功能? 最佳答案 如果
以下 3 个指令之间有区别吗? location ~* \.(png)$ { expires max; log_not_found off; } location ~ \.(png)$ {
位于正文末尾之前的以下脚本在 Internet Explorer 和 Chrome(以及任何其他浏览器)中都会被调用。但重定向到指定的 URL 仅发生在 IE 中。我还尝试了 window.locat
我正在使用 Angular ngRouter。我需要更改 url 路径以及搜索参数。我知道 $location.path 和 $location.search,但是有没有一个函数可以同时设置它们? 最
在angularjs中用$location和window.location哪个更好。 例如,我们可以使用$location.path() 或window.location.href 来完成同样的工作。
我在我的网站上使用上述 2 个命令。似乎它们对 95% 访问它应该触发的页面的人有效,但对其他人则不会。 有谁知道是否可以完全阻止这些 javascript 命令?我真的很头疼为什么它们有时不起作用。
这是我无法弄清楚的另一个错误。 我有这个类ExtendedLocation extends Location实例化时抛出 ClassCastExceptioncurrentGpsLocation =
我一直在尝试简单地将一个包含两个变量(一个字符串和一个位置)的类推送和读取到 firebase,但我一直收到此错误。 **com.google.firebase.database.DatabaseEx
我注意到 iPhone 上的“常用位置”似乎比监控 iOS 访问的应用程序 (https://developer.apple.com/reference/corelocation/clvisit) 使
在我的 javascript 代码中,在某些时候,我需要刷新窗口(用户上传了新图片但在页面中仍然可以看到它) 我想知道为什么 location.href = location.href 不刷新窗口?
我是一名优秀的程序员,十分优秀!