访问外部类Android开发中的内部类变量

时间:2017-02-02 04:23:50

标签: java android

我正在尝试通过我的Onclick功能中的短信发送包含经度,纬度和城市名称的字符串“s”。但是我无法访问此字符串,因为它位于方法的内部类中。这是我的代码:

    package com.horizonsedge.getcurrentlocation;

    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Locale;

    import android.Manifest;
    import android.app.Activity;
    import android.app.AlertDialog;
    import android.app.PendingIntent;
    import android.content.ContentResolver;
    import android.content.Context;
    import android.content.DialogInterface;
    import android.content.Intent;
    import android.content.pm.ActivityInfo;
    import android.content.pm.PackageManager;
    import android.location.Address;
    import android.location.Geocoder;
    import android.location.Location;
    import android.location.LocationListener;
    import android.location.LocationManager;
    import android.net.Uri;
    import android.os.Bundle;
    import android.provider.Settings;
    import android.support.v4.app.ActivityCompat;
    import android.support.v4.content.ContextCompat;
    import android.telephony.SmsManager;
    import android.util.Log;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.ProgressBar;
    import android.widget.Toast;

    import com.google.android.gms.appindexing.Action;
    import com.google.android.gms.appindexing.AppIndex;
    import com.google.android.gms.appindexing.Thing;
    import com.google.android.gms.common.api.GoogleApiClient;

    import static android.Manifest.permission.ACCESS_FINE_LOCATION;
    import static android.Manifest.permission.CAMERA;
    import static android.Manifest.permission.READ_CONTACTS;
    import static android.Manifest.permission.READ_PHONE_STATE;
    import static android.Manifest.permission.SEND_SMS;
    import static android.R.id.message;

  public class GetCurrentLocation extends Activity
    implements OnClickListener {

private LocationManager locationMangaer = null;
private LocationListener locationListener = null;

private Button btnGetLocation = null;
private EditText editLocation = null;
private ProgressBar pb = null;

private static final String TAG = "Debug";
private Boolean flag = false;


public static final int RequestPermissionCode = 1;
/**
 * ATTENTION: This was auto-generated to implement the App Indexing API.
 * See https://g.co/AppIndexing/AndroidStudio for more information.
 */
private GoogleApiClient client;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_get_current_location);


    //if you want to lock screen for always Portrait mode
    setRequestedOrientation(ActivityInfo
            .SCREEN_ORIENTATION_PORTRAIT);

    pb = (ProgressBar) findViewById(R.id.progressBar1);
    pb.setVisibility(View.INVISIBLE);

    editLocation = (EditText) findViewById(R.id.editTextLocation);

    btnGetLocation = (Button) findViewById(R.id.btnLocation);
    btnGetLocation.setOnClickListener(this);

    locationMangaer = (LocationManager)
            getSystemService(Context.LOCATION_SERVICE);

    // ATTENTION: This was auto-generated to implement the App Indexing API.
    // See https://g.co/AppIndexing/AndroidStudio for more information.
    client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}

@Override
public void onClick(View v) {

    flag = displayGpsStatus();
    if (flag) {

        Log.v(TAG, "onClick");

        editLocation.setText("Please!! move your device to" +
                " see the changes in coordinates." + "\nWait..");

        pb.setVisibility(View.VISIBLE);
        locationListener = new MyLocationListener();

        if(checkPermission()){

            Toast.makeText(GetCurrentLocation.this, "All Permissions Granted Successfully", Toast.LENGTH_LONG).show();

        }
        else {

            requestPermission();
        }

        //ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
        //ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.SEND_SMS}, 1);
        //checkAndRequestPermissions();

      /*  if(checkLocationPermission()==false){
            checkLocationPermission();
        }
        else {
            locationMangaer.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 10, locationListener);
        }*/
        locationMangaer.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 10, locationListener);
        String messageToSend = "Please Help my location is " + MyLocationListener.s  ;
        String number = "0435025187";

        SmsManager.getDefault().sendTextMessage(number, null, messageToSend, null,null);
    } else {
        alertbox("Gps Status!!", "Your GPS is: OFF");
    }

    //sendSms("+61435025187","hello");
    //String messageToSend = "this is a message";
    //String number = "0435025187";
    //SmsManager.getDefault().sendTextMessage(number, null, messageToSend, null,null);

}

private void requestPermission() {

    ActivityCompat.requestPermissions(GetCurrentLocation.this, new String[]
            {
                    ACCESS_FINE_LOCATION,
                    SEND_SMS
            }, RequestPermissionCode);

}

@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
    switch (requestCode) {

        case RequestPermissionCode:

            if (grantResults.length > 0) {

                boolean LocationPermission = grantResults[0] == PackageManager.PERMISSION_GRANTED;
                boolean SendSMSPermission = grantResults[1] == PackageManager.PERMISSION_GRANTED;

                if (LocationPermission && SendSMSPermission) {

                    Toast.makeText(GetCurrentLocation.this, "Permission Granted", Toast.LENGTH_LONG).show();
                }
                else {
                    Toast.makeText(GetCurrentLocation.this,"Permission Denied",Toast.LENGTH_LONG).show();

                }
            }

            break;
    }
}

public boolean checkPermission() {

    int FirstPermissionResult = ContextCompat.checkSelfPermission(getApplicationContext(), ACCESS_FINE_LOCATION);
    int SecondPermissionResult = ContextCompat.checkSelfPermission(getApplicationContext(), SEND_SMS);

    return FirstPermissionResult == PackageManager.PERMISSION_GRANTED &&
            SecondPermissionResult == PackageManager.PERMISSION_GRANTED;
}

/*private void sendSms(String phoneNumber, String message) {
    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse( "sms:" + phoneNumber ) );
    intent.putExtra( "sms_body", message );
    startActivity(intent);
}

public boolean checkLocationPermission()
{
    String permission = "android.permission.ACCESS_FINE_LOCATION";
    int res = this.checkCallingOrSelfPermission(permission);
    return (res == PackageManager.PERMISSION_GRANTED);
}

public boolean checkSMSPermission()
{
    String permission = "android.permission.SEND_SMS";
    int res = this.checkCallingOrSelfPermission(permission);
    return (res == PackageManager.PERMISSION_GRANTED);
}

public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
    switch (requestCode) {
        case 1: {
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

            } else {
                // permission denied, boo! Disable the
                // functionality that depends on this permission.
            }
            return;
        }
        // other 'case' lines to check for other
        // permissions this app might request
    }
}*/

/*----Method to Check GPS is enable or disable ----- */
private Boolean displayGpsStatus() {
    ContentResolver contentResolver = getBaseContext()
            .getContentResolver();
    boolean gpsStatus = Settings.Secure
            .isLocationProviderEnabled(contentResolver,
                    LocationManager.GPS_PROVIDER);
    if (gpsStatus) {
        return true;

    } else {
        return false;
    }
}

/*----------Method to create an AlertBox ------------- */
protected void alertbox(String title, String mymessage) {
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setMessage("Your Device's GPS is Disable")
            .setCancelable(false)
            .setTitle("** Gps Status **")
            .setPositiveButton("Gps On",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            // finish the current activity
                            // AlertBoxAdvance.this.finish();
                            Intent myIntent = new Intent(
                                    Settings.ACTION_SECURITY_SETTINGS);
                            startActivity(myIntent);
                            dialog.cancel();
                        }
                    })
            .setNegativeButton("Cancel",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            // cancel the dialog box
                            dialog.cancel();
                        }
                    });
    AlertDialog alert = builder.create();
    alert.show();
}

/**
 * ATTENTION: This was auto-generated to implement the App Indexing API.
 * See https://g.co/AppIndexing/AndroidStudio for more information.
 */
public Action getIndexApiAction() {
    Thing object = new Thing.Builder()
            .setName("GetCurrentLocation Page") // TODO: Define a title for the content shown.
            // TODO: Make sure this auto-generated URL is correct.
            .setUrl(Uri.parse("http://[ENTER-YOUR-URL-HERE]"))
            .build();
    return new Action.Builder(Action.TYPE_VIEW)
            .setObject(object)
            .setActionStatus(Action.STATUS_TYPE_COMPLETED)
            .build();
}

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

    // ATTENTION: This was auto-generated to implement the App Indexing API.
    // See https://g.co/AppIndexing/AndroidStudio for more information.
    client.connect();
    AppIndex.AppIndexApi.start(client, getIndexApiAction());
}

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

    // ATTENTION: This was auto-generated to implement the App Indexing API.
    // See https://g.co/AppIndexing/AndroidStudio for more information.
    AppIndex.AppIndexApi.end(client, getIndexApiAction());
    client.disconnect();
}


/*----------Listener class to get coordinates ------------- */
public class MyLocationListener implements LocationListener {

    @Override
    public void onLocationChanged(Location loc) {

        editLocation.setText("");
        pb.setVisibility(View.INVISIBLE);
        Toast.makeText(getBaseContext(), "Location changed : Lat: " +
                        loc.getLatitude() + " Lng: " + loc.getLongitude(),
                Toast.LENGTH_SHORT).show();
        String longitude = "Longitude: " + loc.getLongitude();
        Log.v(TAG, longitude);
        String latitude = "Latitude: " + loc.getLatitude();
        Log.v(TAG, latitude);


/*----------to get City-Name from coordinates ------------- */
        String cityName = null;
        Geocoder gcd = new Geocoder(getBaseContext(),
                Locale.getDefault());
        List<Address> addresses;
        try {
            addresses = gcd.getFromLocation(loc.getLatitude(), loc
                    .getLongitude(), 1);
            if (addresses.size() > 0)
                System.out.println(addresses.get(0).getLocality());
            cityName = addresses.get(0).getLocality();
        } catch (IOException e) {
            e.printStackTrace();
        }

        String s = longitude + "\n" + latitude +
                "\n\nMy Currrent City is: " + cityName;
        editLocation.setText(s);
    }

    @Override
    public void onProviderDisabled(String provider) {
        // TODO Auto-generated method stub
    }

    @Override
    public void onProviderEnabled(String provider) {
        // TODO Auto-generated method stub
    }

    @Override
    public void onStatusChanged(String provider,
                                int status, Bundle extras) {
        // TODO Auto-generated method stub
    }
}

}

我已经尝试通过MyLocationListener.s访问变量来解决这个问题但是我收到错误“无法解析符号'”

2 个答案:

答案 0 :(得分:2)

在oncreate(全局变量)之前声明变量

 String s;

然后分配值

s = longitude + "\n" + latitude +
            "\n\nMy Currrent City is: " + cityName;

在此之前的任何位置使用变量,确保它不为空

if(!s.isEmpty()&&s!=null)
{ 
//your code
}

答案 1 :(得分:0)

GetCurrentLocation中声明字符串,内部类可以访问外部类字段。