使用警报管理器定期获取经纬度

时间:2019-05-22 09:34:10

标签: android location broadcastreceiver alarmmanager

我想制作一个应用,每5分钟获得latitudelongitude。我有上课。但是我无法使用接收器类警报管理器中的警报管理器来获取纬度和经度。

我有一些错误

Attempt to invoke virtual method 'java.lang.Object android.content.Context.getSystemService(java.lang.String)' on a null object reference

这是我的班级接收人

public class AlarmReceiver extends BroadcastReceiver {

public static final String TYPE_REPEATING = "RepeatingAlarm";
private final int NOTIF_ID_REPEATING_SEND_DATA = 101;
public static final String EXTRA_TYPE = "type";

Context mContext;

@Override
public void onReceive(Context context, Intent intent) {
    String type = intent.getStringExtra(EXTRA_TYPE);
    String latitude = intent.getStringExtra("LATITUDE");
    String longitude = intent.getStringExtra("LONGITUDE");
    int notifId = 0;
    if (type.equalsIgnoreCase(TYPE_REPEATING)) {
        notifId = NOTIF_ID_REPEATING_SEND_DATA;
        getLokasiTerkini(mContext);
        //sendDataToServer(latitude,longitude);
    }
}


private void getLokasiTerkini(Context context) {
    GPSTracker gpsTracker = new GPSTracker(context);
    gpsTracker.getLocation();
    String latitude = String.valueOf(gpsTracker.getLatitude());
    String longitude = String.valueOf(gpsTracker.getLongitude());
    Log.d("GET_LAT_LONG", "getLokasiTerkini: " + latitude + " " + longitude);

}

private void sendDataToServer(final String latitude, final String longitude) {
    String url = "http://192.168.57.121/GetLatLongAndroid/api/addLatLong.php";
    AsyncHttpClient client = new AsyncHttpClient();
    RequestParams requestParams = new RequestParams();
    requestParams.put("latitude", latitude);
    requestParams.put("longitude", longitude);
    client.post(url, requestParams, new JsonHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
            try {
                int value = response.getInt("value");
                if (value == 1) {
                    String message = response.getString("message");
                    Log.d("PESAN", "onSuccess: " + message);

                } else {
                    String message = response.getString("message");
                    Log.d("PESAN", "onSuccess: " + message);
                }

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    });
}


public void setRepeatSendData(Context context, String type, String latitude, String longitude) {
    mContext = context;
    AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    Intent intent = new Intent(context, AlarmReceiver.class);
    intent.putExtra(EXTRA_TYPE, type);
    intent.putExtra("LATITUDE", latitude);
    intent.putExtra("LONGITUDE", longitude);
    int requestCode = NOTIF_ID_REPEATING_SEND_DATA;
    PendingIntent pendingIntent = PendingIntent.getBroadcast(context, requestCode, intent, 0);
    alarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
            SystemClock.elapsedRealtime(),
            1 * 60 * 1000,
            pendingIntent);
    Toast.makeText(context, "Send Repeat Data Activated", Toast.LENGTH_SHORT).show();
}

public void cancelAlarm(Context context) {
    AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    Intent intent = new Intent(context, AlarmReceiver.class);
    int requestcode = NOTIF_ID_REPEATING_SEND_DATA;
    PendingIntent pendingIntent = PendingIntent.getBroadcast(context, requestcode, intent, 0);
    alarmManager.cancel(pendingIntent);
    Toast.makeText(context, "Repeating Alarm Dibatalkan", Toast.LENGTH_SHORT).show();
}

}

这是我的GPSTracker课

public class GPSTracker extends Service implements LocationListener {

// Get Class Name
private static String TAG = GPSTracker.class.getName();

private final Context mContext;

// flag for GPS Status
boolean isGPSEnabled = false;

// flag for network status
boolean isNetworkEnabled = false;

// flag for GPS Tracking is enabled
boolean isGPSTrackingEnabled = false;

Location location;
double latitude;
double longitude;

// How many Geocoder should return our GPSTracker
int geocoderMaxResults = 1;

// 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
public static final long MIN_TIME_BW_UPDATES = 1000 * 60; // 1 minute

// Declaring a Location Manager
protected LocationManager locationManager;

// Store LocationManager.GPS_PROVIDER or LocationManager.NETWORK_PROVIDER information
private String provider_info;

public GPSTracker(Context mContext) {
    this.mContext = mContext;
    getLocation();
}

public void getLocation() {
    try {
        locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);
        isGPSEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

        if (isGPSEnabled) {
            this.isGPSTrackingEnabled = true;

            Log.d(TAG, "Application use GPS Service");

            /*
             * This provider determines location using
             * satellites. Depending on conditions, this provider may take a while to return
             * a location fix.
             */

            provider_info = LocationManager.GPS_PROVIDER;
        } else if (isNetworkEnabled) {
            this.isGPSTrackingEnabled = true;

            Log.d(TAG, "Application use Network State to get GPS coordinates");

            /*
             * This provider determines location based on
             * availability of cell tower and WiFi access points. Results are retrieved
             * by means of a network lookup.
             */
            provider_info = LocationManager.NETWORK_PROVIDER;
        }
        if (!provider_info.isEmpty()) {
            if (ActivityCompat.checkSelfPermission((Activity)mContext, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions((Activity) mContext, new String[]{
                        android.Manifest.permission.ACCESS_FINE_LOCATION
                }, 10);
            }
            locationManager.requestLocationUpdates(provider_info, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
            if (locationManager != null) {
                location = locationManager.getLastKnownLocation(provider_info);
                updateGPSCoordinates();
            }
        }
    } catch (Exception e) {
        //e.printStackTrace();
        Log.e(TAG, "Impossible to connect to LocationManager", e);
    }
}

/**
 * Update GPSTracker latitude and longitude
 */
public void updateGPSCoordinates() {
    if (location != null) {
        latitude = location.getLatitude();
        longitude = location.getLongitude();
    }
}

/**
 * GPSTracker latitude getter and setter
 * @return latitude
 */
public double getLatitude() {
    if (location != null) {
        latitude = location.getLatitude();
    }

    return latitude;
}

/**
 * GPSTracker longitude getter and setter
 * @return
 */
public double getLongitude() {
    if (location != null) {
        longitude = location.getLongitude();
    }

    return longitude;
}

/**
 * GPSTracker isGPSTrackingEnabled getter.
 * Check GPS/wifi is enabled
 */
public boolean getIsGPSTrackingEnabled() {

    return this.isGPSTrackingEnabled;
}

/**
 * Stop using GPS listener
 * Calling this method will stop using GPS in your app
 */
public void stopUsingGPS() {
    if (locationManager != null) {
        locationManager.removeUpdates(GPSTracker.this);
    }
}

/**
 * Function to show settings alert dialog
 */
public void showSettingsAlert() {
    AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

    //Setting Dialog Title
    alertDialog.setTitle(R.string.GPSAlertDialogTitle);

    //Setting Dialog Message
    alertDialog.setMessage(R.string.GPSAlertDialogMessage);

    //On Pressing Setting button
    alertDialog.setPositiveButton(R.string.action_refresh, new DialogInterface.OnClickListener() {

        @Override
        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(R.string.cancel, new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which)
        {
            dialog.cancel();
        }
    });

    alertDialog.show();
}

/**
 * Get list of address by latitude and longitude
 * @return null or List<Address>
 */
public List<Address> getGeocoderAddress(Context context) {
    if (location != null) {

        Geocoder geocoder = new Geocoder(context, Locale.ENGLISH);

        try {
            /**
             * Geocoder.getFromLocation - Returns an array of Addresses
             * that are known to describe the area immediately surrounding the given latitude and longitude.
             */
            List<Address> addresses = geocoder.getFromLocation(latitude, longitude, this.geocoderMaxResults);

            return addresses;
        } catch (IOException e) {
            //e.printStackTrace();
            Log.e(TAG, "Impossible to connect to Geocoder", e);
        }
    }

    return null;
}

/**
 * Try to get AddressLine
 * @return null or addressLine
 */
public String getAddressLine(Context context) {
    List<Address> addresses = getGeocoderAddress(context);

    if (addresses != null && addresses.size() > 0) {
        Address address = addresses.get(0);
        String addressLine = address.getAddressLine(0);

        return addressLine;
    } else {
        return null;
    }
}

/**
 * Try to get Locality
 * @return null or locality
 */
public String getLocality(Context context) {
    List<Address> addresses = getGeocoderAddress(context);

    if (addresses != null && addresses.size() > 0) {
        Address address = addresses.get(0);
        String locality = address.getLocality();

        return locality;
    }
    else {
        return null;
    }
}

/**
 * Try to get Postal Code
 * @return null or postalCode
 */
public String getPostalCode(Context context) {
    List<Address> addresses = getGeocoderAddress(context);

    if (addresses != null && addresses.size() > 0) {
        Address address = addresses.get(0);
        String postalCode = address.getPostalCode();

        return postalCode;
    } else {
        return null;
    }
}

/**
 * Try to get CountryName
 * @return null or postalCode
 */
public String getCountryName(Context context) {
    List<Address> addresses = getGeocoderAddress(context);
    if (addresses != null && addresses.size() > 0) {
        Address address = addresses.get(0);
        String countryName = address.getCountryName();

        return countryName;
    } else {
        return null;
    }
}

public String getFeaturName(Context context){
    List<Address> addresses = getGeocoderAddress(context);
    if (addresses != null && addresses.size() > 0) {
        Address address = addresses.get(0);
        String featureName = address.getFeatureName();

        return featureName;
    }else {
        return null;
    }
}

public String getPremises(Context context) {
    List<Address> addresses = getGeocoderAddress(context);
    if (addresses != null && addresses.size() > 0) {
        Address address = addresses.get(0);
        String premises = address.getPremises();

        return premises;

    }else {
        return null;
    }
}


@Nullable
@Override
public IBinder onBind(Intent intent) {
    return null;
}

@Override
public void onLocationChanged(Location location) {

}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {

}

@Override
public void onProviderEnabled(String provider) {

}

@Override
public void onProviderDisabled(String provider) {

}
}

我希望我的班级GPSTracker从接收者班级访问。

1 个答案:

答案 0 :(得分:0)

无法在BroadcastReceiver中启动LocationManager(您已在此处使用GPSTracker类)。因此,让我们在BroadcastReceiver上使用服务,在该服务中,您可以使用GPSTracker类。

在onReceive方法中编写

Intent serviceIntent = new Intent(context,YourService.class);
context.startService(serviceIntent); //start service for get location