使用异步任务在后台获取经度和纬度
Fetching longitude and latitude in background using Async task
我希望用户按下按钮,按下按钮后 gps 应该在后台自动获取坐标,如你所知 gps 可能需要几分钟来获取坐标,我只希望 gps 花点时间在获取坐标之后执行一个名为 'SendLocationSms'、
的方法
如果我在 doInBackground 中使用 onLocationChanged 方法会报错,
或者如果我不使用异步任务获取坐标,那么我必须等待坐标,获取后我可以按下按钮执行方法 SendLocationSms,
我希望用户只需在 gps 打开时按下一个按钮,然后 gps 就会花费足够多的时间来获取坐标,然后在获取之后自动 运行 我想要的方法而不会注意到用户。
基本上我正在开发一个应用程序,它在按下警报按钮时通过短信发送用户的位置,用户只需打开 gps 并按下警报按钮,应用程序应该完成剩下的工作,我不希望用户等到 gps 获取发送警报的坐标。
请帮帮我
public class MainActivity extends AppCompatActivity implements LocationListener {
private LocationManager n;
private double lat;
private double lot;
private Button save;
private TextView textSMS;
private String gps;
private String sms;
public Button con;
DatabaseHelper myDb;
String id, cell1;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
con = (Button) findViewById(R.id.con);
con.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(MainActivity.this, Contacts.class);
startActivity(i);
}
});
myDb = new DatabaseHelper(this);
Cursor c = myDb.getAllData();
c.moveToFirst();
cell1 = (c.getString(1));
save = (Button) findViewById(R.id.save);
textSMS = (TextView) findViewById(R.id.editTextSMS);
textSMS.setText("Help me please im at: [location]");
sms="Help me please im at: ";
n = (LocationManager) getSystemService(LOCATION_SERVICE);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, 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;
}
n.requestLocationUpdates(LocationManager.GPS_PROVIDER, 60000, 100, this);
save.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if ( gps != null ) {
try {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(cell1.toString(), null, sms + gps, null, null);
Toast.makeText(getApplicationContext(), "Your message sent successfuly !",
Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(getApplicationContext(),
"SMS failddddd!",
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
});
}
@Override
public void onLocationChanged(final Location l) {
this.lat=l.getLatitude();
this.lot=l.getLongitude();
this.gps = "\n" +
"www.google.com/maps/place/"+lat+","+lot;
TextView locc = (TextView) findViewById(R.id.locc);
locc.setTextColor(Color.GREEN);
locc.setText("New Location Fetched !");
Toast.makeText(getApplicationContext(), "Location done", Toast.LENGTH_LONG).show();
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
Toast.makeText(getBaseContext(),"Gps enabled",Toast.LENGTH_LONG).show();
}
@Override
public void onProviderDisabled(String provider) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
Toast.makeText(getBaseContext(), "Gps is turned off!! ",
Toast.LENGTH_SHORT).show();
}
public void showMessage(String title,String Message){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(Message);
builder.show();
}
}
听着,点击 activity 中的按钮,我想通过短信发送经度和纬度,我打开 gps,然后按下按钮,但你知道 gps 需要一两分钟才能获取坐标,所以如果我在获取坐标之前按下按钮当然它会发送 null 作为纬度和经度,所以我希望如果仍然没有 gps 坐标但用户按下按钮,那么应用程序应该等到位置获取然后发送包含纬度和经度的短信.所以这是细节:)希望现在你能帮助我,非常感谢
在您的activity中您需要记录当前位置。
...
private Location currentLocation;
...
@Override
public void onLocationChanged(Location location) {
currentLocation = location;
}
当用户通过短信点击发送位置时,您现在可以在 asyncTask 中使用此变量。
并且不要忘记在您的代码中的某处请求位置更新,例如看这个:
LocationRequest REQUEST = LocationRequest.create() // LocationRequest parameters definition.
.setInterval(30000)
.setFastestInterval(16) // 16ms = 60fps
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
if(googleApiClient.isConnected()){
LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, REQUEST, this);
}
编辑:
您可以执行以下操作。添加一个布尔值,通知用户要发送当前位置,当位置准备就绪时,您可以发送它。因此,您将不得不以这种方式修改您的 onclick 侦听器和位置更新侦听器:
...
private boolean needSendSMS = false;
...
save.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if ( gps != null ) {
try {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(cell1.toString(), null, sms + gps, null, null);
Toast.makeText(getApplicationContext(), "Your message sent successfuly !",
Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(getApplicationContext(),
"SMS failddddd!",
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
else{
needSendSMS = true;
}
}
...
@Override
public void onLocationChanged(Location l) {
this.lat=l.getLatitude();
this.lot=l.getLongitude();
if ( needSendSMS) {
needSendSMS=false;
// Send your sms like you did before.
}
}
我希望用户按下按钮,按下按钮后 gps 应该在后台自动获取坐标,如你所知 gps 可能需要几分钟来获取坐标,我只希望 gps 花点时间在获取坐标之后执行一个名为 'SendLocationSms'、
的方法如果我在 doInBackground 中使用 onLocationChanged 方法会报错, 或者如果我不使用异步任务获取坐标,那么我必须等待坐标,获取后我可以按下按钮执行方法 SendLocationSms,
我希望用户只需在 gps 打开时按下一个按钮,然后 gps 就会花费足够多的时间来获取坐标,然后在获取之后自动 运行 我想要的方法而不会注意到用户。
基本上我正在开发一个应用程序,它在按下警报按钮时通过短信发送用户的位置,用户只需打开 gps 并按下警报按钮,应用程序应该完成剩下的工作,我不希望用户等到 gps 获取发送警报的坐标。
请帮帮我
public class MainActivity extends AppCompatActivity implements LocationListener {
private LocationManager n;
private double lat;
private double lot;
private Button save;
private TextView textSMS;
private String gps;
private String sms;
public Button con;
DatabaseHelper myDb;
String id, cell1;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
con = (Button) findViewById(R.id.con);
con.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(MainActivity.this, Contacts.class);
startActivity(i);
}
});
myDb = new DatabaseHelper(this);
Cursor c = myDb.getAllData();
c.moveToFirst();
cell1 = (c.getString(1));
save = (Button) findViewById(R.id.save);
textSMS = (TextView) findViewById(R.id.editTextSMS);
textSMS.setText("Help me please im at: [location]");
sms="Help me please im at: ";
n = (LocationManager) getSystemService(LOCATION_SERVICE);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, 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;
}
n.requestLocationUpdates(LocationManager.GPS_PROVIDER, 60000, 100, this);
save.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if ( gps != null ) {
try {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(cell1.toString(), null, sms + gps, null, null);
Toast.makeText(getApplicationContext(), "Your message sent successfuly !",
Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(getApplicationContext(),
"SMS failddddd!",
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
});
}
@Override
public void onLocationChanged(final Location l) {
this.lat=l.getLatitude();
this.lot=l.getLongitude();
this.gps = "\n" +
"www.google.com/maps/place/"+lat+","+lot;
TextView locc = (TextView) findViewById(R.id.locc);
locc.setTextColor(Color.GREEN);
locc.setText("New Location Fetched !");
Toast.makeText(getApplicationContext(), "Location done", Toast.LENGTH_LONG).show();
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
Toast.makeText(getBaseContext(),"Gps enabled",Toast.LENGTH_LONG).show();
}
@Override
public void onProviderDisabled(String provider) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
Toast.makeText(getBaseContext(), "Gps is turned off!! ",
Toast.LENGTH_SHORT).show();
}
public void showMessage(String title,String Message){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(Message);
builder.show();
}
}
听着,点击 activity 中的按钮,我想通过短信发送经度和纬度,我打开 gps,然后按下按钮,但你知道 gps 需要一两分钟才能获取坐标,所以如果我在获取坐标之前按下按钮当然它会发送 null 作为纬度和经度,所以我希望如果仍然没有 gps 坐标但用户按下按钮,那么应用程序应该等到位置获取然后发送包含纬度和经度的短信.所以这是细节:)希望现在你能帮助我,非常感谢
在您的activity中您需要记录当前位置。
...
private Location currentLocation;
...
@Override
public void onLocationChanged(Location location) {
currentLocation = location;
}
当用户通过短信点击发送位置时,您现在可以在 asyncTask 中使用此变量。
并且不要忘记在您的代码中的某处请求位置更新,例如看这个:
LocationRequest REQUEST = LocationRequest.create() // LocationRequest parameters definition.
.setInterval(30000)
.setFastestInterval(16) // 16ms = 60fps
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
if(googleApiClient.isConnected()){
LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, REQUEST, this);
}
编辑: 您可以执行以下操作。添加一个布尔值,通知用户要发送当前位置,当位置准备就绪时,您可以发送它。因此,您将不得不以这种方式修改您的 onclick 侦听器和位置更新侦听器:
...
private boolean needSendSMS = false;
...
save.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if ( gps != null ) {
try {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(cell1.toString(), null, sms + gps, null, null);
Toast.makeText(getApplicationContext(), "Your message sent successfuly !",
Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(getApplicationContext(),
"SMS failddddd!",
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
else{
needSendSMS = true;
}
}
...
@Override
public void onLocationChanged(Location l) {
this.lat=l.getLatitude();
this.lot=l.getLongitude();
if ( needSendSMS) {
needSendSMS=false;
// Send your sms like you did before.
}
}