如何从另一个活动中调用一个类?

时间:2015-05-06 01:53:09

标签: class android-activity

我想将MainActivity类调用到另一个活动。这是我的MainActivity.java代码:

package com.blinkedup.geolocationchat;

import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.app.Activity;
import android.app.Service;
import android.view.Menu;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

    TextView textView;
    LocationManager locationManager;
    MyLocationListener locationListener = new MyLocationListener();

    Criteria criteria;
    String bestProvider;
    String listOfBestProviders;


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

        criteria = new Criteria();
        textView = (TextView) findViewById(R.id.textView1);

        criteria.setAccuracy(Criteria.ACCURACY_COARSE);
        criteria.setPowerRequirement(Criteria.POWER_LOW);
        criteria.setAltitudeRequired(false);
        criteria.setBearingRequired(false);
        criteria.setCostAllowed(true);

        locationManager = (LocationManager) getSystemService(Service.LOCATION_SERVICE);
        //locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);

        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);

        bestProvider = locationManager.getBestProvider(criteria, true);

        Toast.makeText(getApplicationContext(), bestProvider, 3).show();
    }

    protected void onPause(){
        super.onPause();
        locationManager.removeUpdates(locationListener);
    }

    private class MyLocationListener implements LocationListener{

        @Override
        public void onLocationChanged(Location location) {
            // TODO Auto-generated method stub
            textView.setText("Latitude: " + location.getLatitude() + 
                    "Longitude: " + location.getLongitude());
        }

        @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

        }

    }

}

在另一个活动中,我想调用上面代码的lat和long,但不想将代码重写为活动。我只是想调用它并在另一个活动中显示结果。请帮忙。感谢

1 个答案:

答案 0 :(得分:0)

使你的变量静态并在onCreate()方法之前定义它,通过这样的调用在另一个活动中使用该变量。

YourMainActivity.yourstaticvariable