3 回答

TA貢獻1865條經驗 獲得超7個贊
您需要將上下文傳遞給fyl類。
一種解決方案是為您的fyl類創建一個類似這樣的構造函數:
public class fyl {
Context mContext;
public fyl(Context mContext) {
this.mContext = mContext;
}
public Location getLocation() {
--
locationManager = (LocationManager)mContext.getSystemService(context);
--
}
}
因此,在您的活動類中,在onCreate函數中創建fyl對象,如下所示:
package com.atClass.lmt;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import android.location.Location;
public class lmt extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
fyl lfyl = new fyl(this); //Here the context is passing
Location location = lfyl.getLocation();
String latLongString = lfyl.updateWithNewLocation(location);
TextView myLocationText = (TextView)findViewById(R.id.myLocationText);
myLocationText.setText("Your current position is:\n" + latLongString);
}
}

TA貢獻1998條經驗 獲得超6個贊
解決這個問題的一種方法是為實例創建一個靜態類。我在AS3中經常使用它,在Android開發中也為我工作得很好。
配置文件
public final class Config {
public static MyApp context = null;
}
MyApp.java
public class MyApp extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Config.context = this;
}
...
}
然后,您可以訪問上下文或通過使用 Config.context
LocationManager locationManager;
String context = Context.LOCATION_SERVICE;
locationManager = Config.context.getSystemService(context);
- 3 回答
- 0 關注
- 1036 瀏覽
添加回答
舉報