我试图让一个线程能够不断地将GPS坐标发送到我的数据库。 这是我的代码:
public class trackThread extends Thread {
Context mContext;
public trackThread(Context mContext) {
this.mContext = mContext;
}
@SuppressLint("MissingPermission")
public void run() {
LocationManager locationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
trackThread.MyCurrentLoctionListener locationListener = new trackThread.MyCurrentLoctionListener();
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
}
public class MyCurrentLoctionListener implements android.location.LocationListener {
@Override
public void onLocationChanged(Location location) {
final String myLocation = "Latitude = " + location.getLatitude() + " Longitude = " + location.getLongitude();
// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(mContext);
String url ="http://example.org/send.php?lat=" + location.getLatitude() + "&long=" + location.getLongitude();
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
// Display the first 500 characters of the response string.
Log.e("Response is: "+ response.toString(), myLocation);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e("That didn't work!", myLocation);
}
});
// Add the request to the RequestQueue.
queue.add(stringRequest);
Log.e("La risposta è ", stringRequest.toString());
}
@Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
@Override
public void onProviderEnabled(String s) {
}
@Override
public void onProviderDisabled(String s) {
}
}
}
此方法在位于Java类中的此方法中调用:
public void inviaGps(View v) {
if ((ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) || ActivityCompat.checkSelfPermission(this, Manifest.permission.INTERNET) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
Toast t = Toast.makeText(this, "Devi abilitare i permessi", Toast.LENGTH_SHORT);
t.show();
return;
}
trackThread p = new trackThread(getApplicationContext());
new Thread(p).start();
}
通过点击简单常见活动的按钮触发此方法。
我认为问题是由错误使用上下文造成的(抱歉,我在Android编码方面不是那么专业)。
P.S。:我还尝试在locationManager.requestLocationUpdates()
下面添加一个简单的Log.e来调试并尝试理解问题。它已经显示给我