0
我正在制定一个定期确定电话坐标并将其上载到数据库的项目。我正在使用的代码是:重新打开应用程序后,LocationManager将不会启动
public class Activity2 extends AppCompatActivity {
private LocationManager locm;
private LocationListener locl;
private Geocoder geocoder;
public TextView text, position;
public double lat, lon;
public String city;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_2);
text = (TextView) findViewById(R.id.textView4);
position = (TextView) findViewById(R.id.textView5);
text.setText("Seriale: " + Build.SERIAL + "\nNome: " + Build.MANUFACTURER + " " + Build.PRODUCT);
geocoder = new Geocoder(getApplicationContext(), Locale.getDefault());
locm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locl = new LocationListener(){
@Override
public void onLocationChanged(Location location) {
try{
lat=location.getLatitude();
lon=location.getLongitude();
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String date = df.format(Calendar.getInstance().getTime());
List<Address> la = geocoder.getFromLocation(lat, lon, 1);
if (la != null & la.size() > 0) {
Address address = la.get(0);
city = address.getLocality();
}
else
{
city="UNKNOWN";
}
MainActivity.st.executeUpdate("INSERT INTO position VALUES ('" + Build.SERIAL + "', '" + date + "', '" + lat + "', '" + lon + "', '" +city + "')");
position.setText(city);
} catch (Exception a){
}
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
};
if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.M) {
if(checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{
Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.INTERNET
}, 10);
return;
}
}else{
locm.requestLocationUpdates("gps", 5000, 0, locl);
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
switch (requestCode){
case 10:
if(grantResults.length>0 && grantResults[0]==PackageManager.PERMISSION_GRANTED) {
try{
locm.requestLocationUpdates("gps", 5000, 0, locl);
}catch (SecurityException e){
}
}
}
}
从干净启动(无缓存/关于以前保存的应用程序数据),它运行良好,按预期工作:
- 启动的第一个活动是一个简单的登录(如果usertext =用户 $$ passtext =文本开始
Activity2
) Activity2
请求的权限(和GPS,如果它是被禁用)- 等待GPS发现其第一位置
- 上传位置每5秒
但是如果我关闭应用程序(不按后退按钮从RAM清洗它),然后我试图再次打开它的Activity2
开始之后,在没有问我用于启用GPS,即使已经启用,它也不再显示位置。让其恢复正常工作的唯一方法是清除内部存储器中的数据。
我该如何解决这个问题?谢谢。
哦,亲爱的!我完全错过了那一个。多快的答案,现在它完美的工作,非常感谢你! – Dadex