【发布时间】:2015-08-26 21:23:55
【问题描述】:
好的,直截了当,我是这个 android 编程的初学者,由于“无法解析方法 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;
}
}}
感谢您的帮助...
【问题讨论】:
-
你可以使用 GPSSample.this
-
它需要构造函数,很抱歉已经更新了问题。我已经将 Activity 和 Listener 分开了。谢谢回答
标签: android android-studio android-context