如何從匿名類Java更新Java中的全局變量

問題描述 投票:1回答:1

我正在嘗試獲取用戶位置的latlng,并將它們作為double傳遞給另一種方法。但是捕鱼游戏能赚钱的,我不知道該怎么做還是有可能的。

一旦我退出內部類捕鱼游戏能赚钱的,變量的值再次變為null。

public class MainActivity extends AppCompatActivity {
    Double lat;
    Double lng;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
    }
    public void onSearch(View v){
        String[] requiredPermissions = {
                Manifest.permission.INTERNET,
                Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.ACCESS_FINE_LOCATION
        };
        boolean ok = true;
        for (int i = 0; i < requiredPermissions.length; i++) {
            int result = ActivityCompat.checkSelfPermission(this, requiredPermissions[i]);
            if (result != PackageManager.PERMISSION_GRANTED) {
                ok = false;
            }
        }
        if (!ok) {
            ActivityCompat.requestPermissions(this, requiredPermissions, 1);
            // that last parameter MUST be >0, or it fails silently
            System.exit(0);
        } else {
            // doStuffThatNeedsPermissions();
            LocationManager lm = (LocationManager) getSystemService(LOCATION_SERVICE);
            lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, new LocationListener() {
                @Override
                public void onLocationChanged(Location location) {
                    lat = location.getLatitude();
                    lng = location.getLongitude();
                    System.out.println("location is : " + lat + lng);
                }
                @Override
                public void onStatusChanged(String s, int i, Bundle bundle) {
                }
                @Override
                public void onProviderEnabled(String s) {
                }
                @Override
                public void onProviderDisabled(String s) {
                }
            });
            //System.out.println("location is here is : " + lat + lng);
        }
        //System.out.println("location is dow here is : " + lat + lng);
    }
}
java android
1個回答
-1
投票

我無權發表評論,所以才回答問題。

據我了解。盡管有很多方法。這里是您可以在整個課程中使用的方法。

private Double lat,lng;
...
@Override
        public void onLocationChanged(Location location) {
            this.lat = location.getLatitude();
            this.lng = location.getLongitude();
            System.out.println("location is : " + this.lat + this.lng);
        }
...
System.out.println("location is here is : " + this.lat + this.lng);

我編輯了答案。我犯了一個愚蠢的錯誤。對此表示抱歉。


推薦問答