当前位置在地理围栏区域上时,应用程序崩溃

时间:2018-09-24 08:27:38

标签: java android geofencing

我创建了一个可检测用户是否在地理围栏区域上的应用。但是问题在于,当我进入地理围栏区域时,该应用程序将关闭。

这是 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 :(得分:0)

MainActivity mainActivity = new MainActivity();

这是错误的。您无法创建这样的活动。此外,您不应该直接从IntentService进行UI更改。什么是应用未打开?然后就没有活动。

您应该做的是,当当前位置在地理围栏区域中时,创建一个Notification。当用户单击通知时,通过在意图中传递“ HANDLED INTENT” 字符串来打开您的活动,然后将此字符串设置为txtPrint。