从活动传递上下文

时间:2015-08-26 12:45:29

标签: android android-studio android-context

好的直到我是这个Android编程的初学者,我有问题如何从我的活动中传递上下文,因为“cant resolve method getapplicationcontext”

这是MyLocationListener.java:

 public class MyLocationListener implements LocationListener {
        // Dipanggil saat ada perubahan lokasi geografis pengguna

private Context mContext;

    public MyLocationListener(Context context) {
        mContext = context;
    }

        @Override
        public void onLocationChanged(Location location) {
    // Mendapatkan nilai latitude dari lokasi terbaru
            double latitude = location.getLatitude();

    // Mendapatkan nilai longitude dari lokasi terbaru
            double longitude = location.getLongitude();

    // Menampilkan lokasi terbaru menggunakan Toast
            String message = "Lokasi saat ini :\n" +
                    "Latitude  = " + latitude + "\n" +
                    "Longitude = " + longitude;
            Toast.makeText(getApplicationContext(),
                    message, Toast.LENGTH_LONG).show();
        }

        // Dipanggil saat provider dinon-aktifkan oleh pengguna
        @Override
        public void onProviderDisabled(String provider) {
            String message = "GPS disabled";
            Toast.makeText(getApplicationContext(),
                    message, Toast.LENGTH_LONG).show();
        }

        // dipanggil saat provider diaktifkan oleh pengguna
        @Override
        public void onProviderEnabled(String provider) {
            String message = "GPS enabled";
            Toast.makeText(getApplicationContext(),
                    message, Toast.LENGTH_LONG).show();
        }

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

这是我的活动(GPSSample.java):

public class GPSSample extends Activity {
        /** Called when the activity is first created. */
        @Override

LocationListener myLocationListener = new MyLocationListener(this);

        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

    // Inisiasi LocationManager dan LocationListener
            LocationManager myLocationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
            LocationListener myLocationListener = new MyLocationListener();
            myLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, myLocationListener);
        }

它说我应该使用构造函数来传递它,但是如何? 我有一些构造函数示例,但我不知道在哪里放置它,并根据我的脚本重命名

MyClass myClass = new MyClass(this);

然后在该类中创建一个构造函数,该构造函数接受Context作为参数并使用

public class MyClass  
{ 
    Context c;
    public MyClass(Context context)
    { 
         c= context;
     } 
}} 

感谢您的帮助...

0 个答案:

没有答案