我想在我的应用程序上运行一个locationlistener,它每10m或每5秒发送一次新的“ Popup”。稍后,我会将数据发送到云中。
这是我的GPSTracker类别:
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.util.Log;
import android.widget.Toast;
public class GPSTracker extends Service implements LocationListener {
private final Context mContext;
// flag for GPS status
boolean isGPSEnabled = false;
// flag for network status
boolean isNetworkEnabled = false;
// flag for GPS status
boolean canGetLocation = false;
Location location; // location
double latitude; // latitude
double longitude; // longitude
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 5 * 1; // 1 minute
// Declaring a Location Manager
protected LocationManager locationManager;
public GPSTracker(Context context) {
this.mContext = context;
getLocation();
}
public Location getLocation() {
try {
locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
} else {
this.canGetLocation = true;
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
/**
* Stop using GPS listener
* Calling this function will stop using GPS in your app
* */
public void stopUsingGPS(){
if(locationManager != null){
locationManager.removeUpdates(GPSTracker.this);
}
}
/**
* Function to get latitude
* */
public double getLatitude(){
if(location != null){
latitude = location.getLatitude();
}
// return latitude
return latitude;
}
/**
* Function to get longitude
* */
public double getLongitude(){
if(location != null){
longitude = location.getLongitude();
}
// return longitude
return longitude;
}
/**
* Function to check GPS/wifi enabled
* @return boolean
* */
public boolean canGetLocation() {
return this.canGetLocation;
}
/**
* Function to show settings alert dialog
* On pressing Settings button will lauch Settings Options
* */
public void showSettingsAlert(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
// Setting Dialog Title
alertDialog.setTitle("GPS is settings");
// Setting Dialog Message
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
// On pressing Settings button
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
// on pressing cancel button
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
@Override
public void onLocationChanged(Location location) {
}
@Override
public void onProviderDisabled(String provider) {
}
@Override
public void onProviderEnabled(String provider) {
Toast.makeText(GPSTracker.this,"Provider enabled by the user. GPS turned on",Toast.LENGTH_LONG).show();
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public IBinder onBind(Intent arg0) {
return null;
}
}
对于我的活动课,我做到了:
gps = new GPSTracker(MainActivity.this);
double latitude2 = gps.getLatitude();
double longitude2 = gps.getLongitude();
我收到数据,可以正常工作。但是现在我想在后台运行数据,因此当位置更改时,我可以实现一个将数据发送到云的功能。
我尝试了这个:
private void startGPSTrackerInBackground() {
new AsyncTask<Void,Void,String>() {
@Override
protected String doInBackground(Void... params) {
String msg = "This message runs in background";
gps = new GPSTracker(MainActivity.this);
if(!gps.canGetLocation()){
gps.showSettingsAlert();
}else{
gps = new GPSTracker(MainActivity.this);
double latitude2 = gps.getLatitude();
double longitude2 = gps.getLongitude();
}
return msg;
}
@Override
protected void onPostExecute(String msg) {
mDisplay.append(msg + "\n");
}
}.execute(null, null, null);
}
但是在此功能中,无法获取我的GPSTracker类的信息,有人想办法做到这一点吗?
最佳答案
创建一个独立的类,添加一个GPSTracker
成员变量并将其传递给构造函数。将任务包装在可以稍后调用的方法中:
public class BackgroundGPSTracker() {
GPSTracker tracker;
public BackgroundGPSTracker(GPSTracker tracker) {
this.tracker = tracker;
}
public void run() {
new AsyncTask<Void,Void,String>() {
@Override
protected String doInBackground(Void... params) {
// Do some background stuff.
}
@Override
protected void onPostExecute(String msg) {
// Do after work stuff
}
}.execute(null, null, null);
}
}
采用:
如果您这样创建GPSTracker:
gps = new GPSTracker(MainActivity.this);
然后,您开始将其传递给任务的活动:
BackgroundGPSTracker bgGPSTracker= new BackgroundGPSTracker(gps);
bgGPSTracker.run();
编辑
使用成员变量存储最近的已知位置,并使用计时器安排更新时间:
public class CampaignsDiscoverActivity extends Activity{
static final int QUERY_CAMPAINGS_DELAY = 30000;// milliseconds
Location currentLocation;
Timer timer;
void restartTimer() {
timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
sendDataToServerOrWhatever();
}
}, QUERY_CAMPAINGS_DELAY, QUERY_CAMPAINGS_DELAY);
}
void stopTimer() {
if (timer != null) {
timer.cancel();
timer = null;
}
}
void sendDataToServerOrWhatever() {
// Do some stuff using currentLocation
}
设置位置更改的监听器。引发位置更改时,请停止计时器,开始工作并重新启动它:
void startGPSUpdates() {
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationListener = new LocationListener() {
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
@Override
public void onLocationChanged(Location location) {
stopTimer();
currentLocation = location;
sendDataToServerOrWhatever();
}
};
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
// Initialize location.
currentLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (currentLocation == null) {
currentLocation = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
restartTimer();
}
要启动系统,只需调用
startGPSUpdates
。当应用程序进入后台时,您应该暂停监听器,而当前台进入时,您应该恢复监听器:
@Override
public void onPause() {
super.onPause();
if (applicationData.isLoggedIn()) {
pauseLocationUpdates();
}
}
@Override
public void onResume() {
super.onResume();
if (applicationData.isLoggedIn()) {
resumeLocationUpdates();
}
}
void pauseLocationUpdates() {
locationManager.removeUpdates(locationListener);
}
void resumeLocationUpdates() {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
}
我认为您应该对计时器执行相同的操作,但是我使用它的应用尚未完成且尚未经过全面测试,因此您可能会发现错误。
希望能有所帮助。