我可以将地理围栏意图放在同一个班上吗?

时间:2018-09-24 11:27:27

标签: java android geofencing android-geofence

我正在尝试创建一个仅在用户位于地理围栏内时通知用户的应用程序。该应用程序正在运行。我只想知道 GeofenceService.java 类是否可以放入 MainActivity.java

这是 MainActivity.java

上的代码
public class MainActivity extends AppCompatActivity {

    public static final String GEOFENCE_ID = "MyGeofenceId";
    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);
        }
    }

    @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) {
        txtPrint.append("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(1,1, 200) // just some random coordinates
                    .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.java

上的代码
public class GeofenceService extends IntentService {

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

    @Override
    protected void onHandleIntent(@Nullable Intent intent) {

        GeofencingEvent geofencingEvent = GeofencingEvent.fromIntent(intent);
        // handled 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){
                // entered geofence
                NotificationCompat.Builder mBuilder =
                        new NotificationCompat.Builder(this)
                                .setSmallIcon(R.mipmap.ic_launcher)
                                .setContentTitle("Entered Geofence")
                                .setContentText("You are inside the geofence");
                NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
                        mNotificationManager.notify(001, mBuilder.build());
            }else if(transition == Geofence.GEOFENCE_TRANSITION_EXIT){
                //exited geofence
                NotificationCompat.Builder mBuilder =
                        new NotificationCompat.Builder(this)
                                .setSmallIcon(R.mipmap.ic_launcher)
                                .setContentTitle("Exited Geofence")
                                .setContentText("You are outside the geofence");
                NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
                mNotificationManager.notify(001, mBuilder.build());
            }
        }
    }
}

我还将其放在 AndroidManifest.xml

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

0 个答案:

没有答案