地点选择器快速关闭

时间:2017-09-14 18:33:12

标签: java android google-maps google-maps-api-3 android-geofence

我在项目中使用地方选择器让用户添加新位置。用户单击“添加新位置”按钮后,“放置选择器”界面将打开,但问题是它只会打开1-2秒并关闭。下面是我的清单,主要活动和gradle的代码。

的AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.h.autoss2">

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">

    <meta-data
        android:name="com.google.android.geo.API_KEY"
        android:value="my key" />

    <activity android:name="com.example.h.autoss2.MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <provider
        android:name="com.example.h.autoss2.provider.PlaceContentProvider"
        android:authorities="com.example.h.autoss2"
        android:exported="false"/>

</application>

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

MainActivity.java

    public class MainActivity extends AppCompatActivity implements
    ConnectionCallbacks,
    OnConnectionFailedListener {

    // Constants
public static final String TAG = MainActivity.class.getSimpleName();
private static final int PERMISSIONS_REQUEST_FINE_LOCATION = 111;
private static final int PLACE_PICKER_REQUEST = 1;

// Member variables
private PlaceListAdapter mAdapter;
private RecyclerView mRecyclerView;
private boolean mIsEnabled;
private GoogleApiClient mClient;
private Geofencing mGeofencing;

/**
 * Called when the activity is starting
 *
 * @param savedInstanceState The Bundle that contains the data supplied in onSaveInstanceState
 */
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // Set up the recycler view
    mRecyclerView = (RecyclerView) findViewById(R.id.places_list_recycler_view);
    mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
    mAdapter = new PlaceListAdapter(this, null);
    mRecyclerView.setAdapter(mAdapter);


    Switch onOffSwitch = (Switch) findViewById(R.id.enable_switch);
    mIsEnabled = getPreferences(MODE_PRIVATE).getBoolean(getString(R.string.setting_enabled), false);
    onOffSwitch.setChecked(mIsEnabled);
    onOffSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit();
            editor.putBoolean(getString(R.string.setting_enabled), isChecked);
            mIsEnabled = isChecked;
            editor.commit();
            if (isChecked) mGeofencing.registerAllGeofences();
            else mGeofencing.unRegisterAllGeofences();
        }

    });


           mClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .addApi(Places.GEO_DATA_API)
            .enableAutoManage(this, this)
            .build();

    mGeofencing = new Geofencing(this, mClient);

}

/***
 * Called when the Google API Client is successfully connected
 *
 * @param connectionHint Bundle of data provided to clients by Google Play services
 */
@Override
public void onConnected(@Nullable Bundle connectionHint) {
    refreshPlacesData();
    Log.i(TAG, "API Client Connection Successful!");
}

/***
 * Called when the Google API Client is suspended
 *
 * @param cause cause The reason for the disconnection. Defined by constants CAUSE_*.
 */
@Override
public void onConnectionSuspended(int cause) {
    Log.i(TAG, "API Client Connection Suspended!");
}

/***
 * Called when the Google API Client failed to connect to Google Play Services
 *
 * @param result A ConnectionResult that can be used for resolving the error
 */
@Override
public void onConnectionFailed(@NonNull ConnectionResult result) {
    Log.e(TAG, "API Client Connection Failed!");
}

public void refreshPlacesData() {
    Uri uri = PlaceContract.PlaceEntry.CONTENT_URI;
    Cursor data = getContentResolver().query(
            uri,
            null,
            null,
            null,
            null);

    if (data == null || data.getCount() == 0) return;
    List<String> guids = new ArrayList<String>();
    while (data.moveToNext()) {
        guids.add(data.getString(data.getColumnIndex(PlaceContract.PlaceEntry.COLUMN_PLACE_ID)));
    }
    PendingResult<PlaceBuffer> placeResult = Places.GeoDataApi.getPlaceById(mClient,
            guids.toArray(new String[guids.size()]));
    placeResult.setResultCallback(new ResultCallback<PlaceBuffer>() {
        @Override
        public void onResult(@NonNull PlaceBuffer places) {
            mAdapter.swapPlaces(places);
            mGeofencing.updateGeofencesList(places);
            if (mIsEnabled) mGeofencing.registerAllGeofences();
        }
    });
}


public void onAddPlaceButtonClicked(View view) {
    if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION)
            != PackageManager.PERMISSION_GRANTED) {
        Toast.makeText(this, getString(R.string.need_location_permission_message), Toast.LENGTH_LONG).show();
        return;
    }
    try {

        PlacePicker.IntentBuilder builder = new PlacePicker.IntentBuilder();

        startActivityForResult(builder.build(this), PLACE_PICKER_REQUEST);
    } catch (GooglePlayServicesRepairableException e) {
        Log.e(TAG, String.format("GooglePlayServices Not Available [%s]", e.getMessage()));
    } catch (GooglePlayServicesNotAvailableException e) {
        Log.e(TAG, String.format("GooglePlayServices Not Available [%s]", e.getMessage()));
    } catch (Exception e) {
        Log.e(TAG, String.format("PlacePicker Exception: %s", e.getMessage()));
    }
}


/***
 * Called when the Place Picker Activity returns back with a selected place (or after canceling)
 *
 * @param requestCode The request code passed when calling startActivityForResult
 * @param resultCode  The result code specified by the second activity
 * @param data        The Intent that carries the result data.
 */
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == PLACE_PICKER_REQUEST && resultCode == RESULT_OK) {
        Place place = PlacePicker.getPlace(this, data);
        if (place == null) {
            Log.i(TAG, "No place selected");
            return;
        }

        String placeID = place.getId();

        // Insert a new place into DB
        ContentValues contentValues = new ContentValues();
        contentValues.put(PlaceContract.PlaceEntry.COLUMN_PLACE_ID, placeID);
        getContentResolver().insert(PlaceContract.PlaceEntry.CONTENT_URI, contentValues);

        // Get live data information
        refreshPlacesData();
    }
}

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

    // Initialize location permissions checkbox
    CheckBox locationPermissions = (CheckBox) findViewById(R.id.location_permission_checkbox);
    if (ActivityCompat.checkSelfPermission(MainActivity.this,
            android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        locationPermissions.setChecked(false);
    } else {
        locationPermissions.setChecked(true);
        locationPermissions.setEnabled(false);
    }

    // Initialize ringer permissions checkbox
    CheckBox ringerPermissions = (CheckBox) findViewById(R.id.ringer_permissions_checkbox);
    NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    // Check if the API supports such permission change and check if permission is granted
    if (android.os.Build.VERSION.SDK_INT >= 24 && !nm.isNotificationPolicyAccessGranted()) {
        ringerPermissions.setChecked(false);
    } else {
        ringerPermissions.setChecked(true);
        ringerPermissions.setEnabled(false);
    }
}

public void onRingerPermissionsClicked(View view) {
    Intent intent = new Intent(android.provider.Settings.ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS);
    startActivity(intent);
}

public void onLocationPermissionClicked(View view) {
    ActivityCompat.requestPermissions(MainActivity.this,
            new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
            PERMISSIONS_REQUEST_FINE_LOCATION);
}

}

Build.gradle(app module)

apply plugin: 'com.android.application'

android {
compileSdkVersion 23
buildToolsVersion "23.0.3"

defaultConfig {
applicationId "com.example.h.autoss2"
minSdkVersion 16
targetSdkVersion 23
versionCode 1
versionName "1.0"
}
buildTypes {
release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 
'proguard-rules.pro'
    }
}
}

dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.google.android.gms:play-services:9.2.0'
compile 'com.android.support:appcompat-v7:23.4.0'
compile 'com.android.support:recyclerview-v7:23.0.0'
compile 'com.google.android.gms:play-services-places:9.2.0'
compile 'com.google.android.gms:play-services-location:9.2.0'
}

0 个答案:

没有答案