Приложение вылетает, когда текущее местоположение находится в области геозоны - PullRequest
0 голосов
/ 24 сентября 2018

Я создал приложение, которое определяет, находится ли пользователь в области геозоны.Но проблема в том, что когда я вхожу в область геозоны, приложение закрывается.

Вот код в MainActivity.class

public class MainActivity extends AppCompatActivity {

public static final String GEOFENCE_ID = "MyGeofenceId";
public static double lat = 1; //just some random coordinates
public static double lng = 1; //just some random coordinates
GoogleApiClient googleApiClient = null;
private Button startLoc, startGeo, stopGeo;
private TextView txtPrint;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    startLoc = (Button) findViewById(R.id.startloc);
    startGeo = (Button) findViewById(R.id.startgeo);
    stopGeo = (Button) findViewById(R.id.stopgeo);
    txtPrint = (TextView) findViewById(R.id.txtPrint);

    googleApiClient = new GoogleApiClient.Builder(this)
            .addApi(LocationServices.API)
            .addConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks() {
                @Override
                public void onConnected(@Nullable Bundle bundle) {
                    txtPrint.append("Connected to GoogleApiClient");
                }

                @Override
                public void onConnectionSuspended(int i) {
                    txtPrint.append("Suspended connection to GoogleApiClient");
                }
            })
            .addOnConnectionFailedListener(new GoogleApiClient.OnConnectionFailedListener() {
                @Override
                public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
                    txtPrint.append("Failed to connect to GoogleApiClient" + connectionResult.getErrorMessage());
                }
            })
            .build();

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        requestPermissions(new String[] {Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, 1234);
    }
}

public void setTextPrint(String text){
    txtPrint.setText(text);
}

@Override
protected void onResume() {
    super.onResume();

    int response = GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(this);
    if(response != ConnectionResult.SUCCESS){
        txtPrint.append("Google Play Services not available - show dialog to ask user to download it");
        GoogleApiAvailability.getInstance().getErrorDialog(this, response, 1).show();
    }else{
        txtPrint.append("Google Play Services is available - no action required");
    }
}

public void startLocationMonitoring(View view) {
    setTextPrint("startLoc");
    try{
        LocationRequest locationRequest = LocationRequest.create()
                .setInterval(10000)
                .setFastestInterval(5000)
                // .setNumUpdates(5)
                .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, new LocationListener() {
            @Override
            public void onLocationChanged(Location location) {
                txtPrint.append("Location update lat/long " + location.getLatitude() + " " + location.getLongitude());
            }
        });
    }catch (SecurityException e){
        txtPrint.append("Security Exception - " + e.getMessage());
    }
}

public void startGeofenceMonitoring(View view) {
    txtPrint.append("startGeo");

    try{
        Geofence geofence = new Geofence.Builder()
                .setRequestId(GEOFENCE_ID)
                .setCircularRegion(lat, lng, 200)
                .setExpirationDuration(Geofence.NEVER_EXPIRE)
                .setNotificationResponsiveness(1000)
                .setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER | Geofence.GEOFENCE_TRANSITION_EXIT)
                .build();

        GeofencingRequest geofencingRequest = new GeofencingRequest.Builder()
                .setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_ENTER)
                .addGeofence(geofence).build();

        Intent intent = new Intent(this, GeofenceService.class);
        PendingIntent pendingIntent = PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

        if(!googleApiClient.isConnected()){
            txtPrint.append("GoogleApiClient is not connected");
        }else{
            LocationServices.GeofencingApi.addGeofences(googleApiClient, geofencingRequest, pendingIntent)
                    .setResultCallback(new ResultCallback<Status>() {
                        @Override
                        public void onResult(@NonNull Status status) {
                            if(status.isSuccess()){
                                txtPrint.append("Successfully added geofence");
                            }else{
                                txtPrint.append("Failed to add geofence - " + status.getStatus());
                            }
                        }
                    });
        }
    }catch (SecurityException e){
        txtPrint.append("Security Exception - " + e.getMessage());
    }
}

public void stopGeofenceMonitoring(View view) {
    txtPrint.append("stopGeo");
    ArrayList<String> geofenceIds = new ArrayList<String>();
    geofenceIds.add(GEOFENCE_ID);
    LocationServices.GeofencingApi.removeGeofences(googleApiClient, geofenceIds);
}

@Override
protected void onStart() {
    super.onStart();
    googleApiClient.reconnect();
}

@Override
protected void onStop() {
    super.onStop();
    googleApiClient.disconnect();
}
}

Другой класс, который содержитнамеренный обработчик. GeofenceService.class

public class GeofenceService extends IntentService {

public GeofenceService() {
    super("GeofenceService");
}

@Override
protected void onHandleIntent(@Nullable Intent intent) {
    MainActivity mainActivity = new MainActivity();
    mainActivity.setTextPrint("HANDLED INTENT");
    GeofencingEvent geofencingEvent = GeofencingEvent.fromIntent(intent);
    if(geofencingEvent.hasError()){
        // handle error
    }else{

        int transition = geofencingEvent.getGeofenceTransition();
        List<Geofence> geofences = geofencingEvent.getTriggeringGeofences();
        Geofence geofence = geofences.get(0);
        String requestId = geofence.getRequestId();

        if(transition == Geofence.GEOFENCE_TRANSITION_ENTER){
            mainActivity.setTextPrint("Entered Geofence");
        }else if(transition == Geofence.GEOFENCE_TRANSITION_EXIT){
            mainActivity.setTextPrint("Exited Geofence");
        }
    }
}
}

Я также поместил класс GeofenceService в манифест Android

<service android:name=".GeofenceService" android:exported="true" 
 android:enabled="true"></service>

В файле xml есть 3 кнопки, которые вызывают startLocationMonitoring , startGeofenceMonitoring и stopGeofenceMonitoring

Местоположение обновляется, я могу добавить и удалить геозону.Но когда текущее местоположение находится в области геозоны, приложение закрывается.

1 Ответ

0 голосов
/ 24 сентября 2018
MainActivity mainActivity = new MainActivity();

Это неправильно.Вы не можете создать такую ​​деятельность.Более того, вы не должны вносить изменения в пользовательский интерфейс прямо из вашего IntentService.Что такое приложение не открыто?Тогда нет активности.

Что вы должны делать, когда текущее местоположение находится в области геозоны, создать Уведомление .Когда пользователь нажимает на уведомление, откройте свою активность, передав строку "HANDLED INTENT" в намерении, а затем установите для этой строки значение txtPrint.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...