每5秒钟我要向Android应用程序中的Web应用程序当前的经度。如果用户登录该应用程序,那么我们通过放置按钮来使用用户日志。如果用户点击注销按钮,我需要通过另一个按钮(登录)停止当前在同一活动页面上运行的处理程序线程
我已经做了所有事情,但是在停止线程时,我的应用程序崩溃了
如果用户点击登录按钮,它将每5秒自动发送一次数据
private void techlocation() {
handler = new Handler ();
locationManager = (LocationManager) User_deatils .this.getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE); // Choose your accuracy requirement.
locationManager.getBestProvider(criteria, true);
if (ActivityCompat.checkSelfPermission(User_deatils.this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(User_deatils.this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != 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.
return;
}
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 8000, 10, (LocationListener) User_deatils .this);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 8000, 10, (LocationListener) User_deatils .this);
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
lat = location.getLatitude();
lon = location.getLongitude();
}
handler.postDelayed(runLocation, 5000);
}
这是可运行线程将数据发送到服务器端
public Runnable runLocation = new Runnable() {
@Override
public void run() {
latitude = String.valueOf(lat);
longitude = String.valueOf(lon);
arrLat.add(latitude);
arrLng.add(longitude);
User_deatils.this.handler.postDelayed(User_deatils.this.runLocation, 50000);
handler.removeCallbacksAndMessages(this);
Log.e("msg", "new" + handler);
}
}
登录按钮
b3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
.// SaveButtonState("b3");
techlocation(); // calling handler threads
}
});
退出按钮
b4.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
handler.removeCallbacksAndMessages(runLocation);
}
});
答案 0 :(得分:0)
要开始运行并每5秒钟执行一次操作。
用runnable
声明boolean
。
//如果处理程序应停止,则应将其设置为true
boolean mStopHandler = false;
private Handler mHandler;
//initialize runnable in oncreate()
mHandler=new Handler();
Runnable runnable = new Runnable() {
@Override
public void run() {
// do your stuff here
if (!mStopHandler) {
mHandler.postDelayed(this, 5000);
}
}
};
调用此按钮以在按钮
runnable
上启动click()
// start runnable
mHandler.post(runnable);
最后使用它来停止运行
handler.removeCallbacks(runnable);