我有一个Activity,我想调用GPS类的函数来返回地址字符串

时间:2017-12-29 08:13:53

标签: java android gps

这是我的活动,我想获得我正在进行其他活动的地址字符串。但我不知道怎么称呼它。我需要在第二个类中使用一个方法,以便它返回String。

public class GPS extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, GoogleApiClient.OnConnectionFailedListener {

Context mContext = this;
FindGps findGps;
private TextView loc;

private TextView fullname;
private TextView email;
private ImageView profile_image;

private String mUsername, mEmail;


private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mToggle;
private Toolbar mToolbar;


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

    mToolbar = (Toolbar) findViewById(R.id.my_toolbar);
    setSupportActionBar(mToolbar);
    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    mToggle = new ActionBarDrawerToggle(this,mDrawerLayout,R.string.open,R.string.close);
    mDrawerLayout.addDrawerListener(mToggle);
    mToggle.syncState();
    loc = mToolbar.findViewById(R.id.address);
    findGps.findLocation();


    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    NavigationView navigationView = (NavigationView) findViewById(R.id.navigationView);
    navigationView.setNavigationItemSelectedListener(this);
    View header = navigationView.getHeaderView(0);


    fullname = header.findViewById(R.id.name);
    email = header.findViewById(R.id.email);
    profile_image =  header.findViewById(R.id.profileImage);

    sharedPrefManager = new SharedPrefManager(mContext);
    mUsername = sharedPrefManager.getName();
    mEmail = sharedPrefManager.getUserEmail();
    String uri = sharedPrefManager.getPhoto();
    Uri mPhotoUri = Uri.parse(uri);

    fullname.setText(mUsername);
    email.setText(mEmail);
    Picasso.with(mContext)
            .load(mPhotoUri)
            .placeholder(android.R.drawable.menuitem_background)
            .error(android.R.drawable.menuitem_background)
            .into(profile_image);
    configureSignIn();

}

private void configureSignIn() {

        GoogleSignInOptions options = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestEmail()
                .build();

        // Build a GoogleApiClient with access to GoogleSignIn.API and the options above.
        mGoogleApiClient = new GoogleApiClient.Builder(mContext)
                .enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */)
                .addApi(Auth.GOOGLE_SIGN_IN_API, options)
                .build();
        mGoogleApiClient.connect();
}
//method to logout
private void signOut(){
    new SharedPrefManager(mContext).clear();
    mAuth.signOut();

    Auth.GoogleSignInApi.revokeAccess(mGoogleApiClient).setResultCallback(
            new ResultCallback<Status>() {
                @Override
                public void onResult(@NonNull Status status) {
                    Intent intent = new Intent(GPS.this, MainActivity.class);
                    startActivity(intent);
                    finish();
                }
            }
    );
    sharedPrefManager.clear();

}


@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if(mToggle.onOptionsItemSelected(item)){
        return true;
    }

    return super.onOptionsItemSelected(item);
}

@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
   int id=item.getItemId();

        if(id == R.id.nav_account) {
            Toast.makeText(this,"Account Edit Here",Toast.LENGTH_SHORT).show();
        }
       if (id == R.id.settings) {
            Toast.makeText(this,"Settings",Toast.LENGTH_SHORT).show();
        }
        if (id == R.id.logout) {
            signOut();
            //sharedPrefManager.clearUserName(GPS.this);
        }
            //close navigation drawer
    mDrawerLayout.closeDrawer(GravityCompat.START);
    return true;
}

@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

}

现在我有一个可以获取带地址的位置的活动。

public String findLocation()
{
    String address=null;
    Location location = null;
    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    gps = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
    if(!gps)
    {

    }
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
        if (checkSelfPermission(android.Manifest.permission.ACCESS_FINE_LOCATION)!= PackageManager.PERMISSION_GRANTED
                && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION)!=
                PackageManager.PERMISSION_GRANTED){
            requestPermissions(new String[]
                    {android.Manifest.permission.ACCESS_FINE_LOCATION, android.Manifest.permission.ACCESS_COARSE_LOCATION,
                            android.Manifest.permission.INTERNET},10);
            //return;
        }
        else {
            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,3000,0,this);
        }
    }
    Latitude = location.getLatitude();
    Longitude = location.getLongitude();
    String str = Latitude + "  " + Longitude;

    Log.d("Lat lng:",str);
    Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault());
    try {
        List<Address> addressList = geocoder.getFromLocation(Latitude,Longitude,1);
        if (addressList!=null && addressList.size()>0)
        {
            String cityName = addressList.get(0).getLocality().toString();
            String sublocal = addressList.get(0).getSubLocality().toString();
            address = sublocal + ", " +cityName;
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    return address;
}

@Override
public void onLocationChanged(Location location) {

}

@Override
public void onStatusChanged(String s, int i, Bundle bundle) {

}

@Override
public void onProviderEnabled(String s) {

}

@Override
public void onProviderDisabled(String s) {

}

但是,在mainActivity loc = mToolbar.findViewById(R.id.address); findGps.findLocation();中 这是我被困的地方。我如何获得字符串?

1 个答案:

答案 0 :(得分:1)

LocationListener活动中实施GPS,就像

一样
public class GPS extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, GoogleApiClient.OnConnectionFailedListener, LocationListener  {

获取地址的另一种方法,只需在需要时拨打getCompleteAddressString()

private String getCompleteAddressString() {

    LocationManager locationManager;
    Location location;
    double latitude, longitude;
    String strAdd = "";
    locationManager = (LocationManager) this.getSystemService(LOCATION_SERVICE);
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // TODO: Consider calling
        //    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.
        return null;
    }
    location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
    if (location != null) {
        latitude = location.getLatitude();
        longitude = location.getLongitude();
        Log.d("old", "lat :  " + latitude);
        Log.d("old", "long :  " + longitude);

        Geocoder geocoder = new Geocoder(this, Locale.getDefault());
        try {
            List<android.location.Address> addresses = geocoder.getFromLocation(latitude, longitude, 1);
            if (addresses != null) {
                android.location.Address returnedAddress = addresses.get(0);
                StringBuilder strReturnedAddress = new StringBuilder("");

                for (int i = 0; i <= returnedAddress.getMaxAddressLineIndex(); i++) {
                    strReturnedAddress.append(returnedAddress.getAddressLine(i)).append("\n");
                }
                strAdd = strReturnedAddress.toString();

            } else {
                strAdd = "No Address returned!";
            }
        } catch (Exception ex) {
            strAdd = "Canont get Address!";
        }
    }
    return strAdd;
}