【问题标题】:How to use classes that extends Activity in Android?如何在 Android 中使用扩展 Activity 的类?
【发布时间】:2013-12-28 11:09:17
【问题描述】:

我是 Android 编程新手。

基本上我想做的是编写一个扩展Activity的类,然后在另一个也扩展Activity的类中使用它。

就我而言,我想做的是能够使用 GsmCellLocation 类成员,而无需初始化 TelephonyManager

所以我创建了一个名为CellInformation 的类,内容如下:

public class CellInformation extends Activity {

    private TelephonyManager tm;
    private GsmCellLocation cellLoc;

    public CellInformation() { 
        tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
        cellLoc = (GsmCellLocation) tm.getCellLocation();
    }

    public GsmCellLocation updateCellInfo() {
        cellLoc = (GsmCellLocation) tm.getCellLocation();
        return cellLoc;
    }

    public int getCid() {
        return (cellLoc.getCid()%65536);
    }

    public int getLac() {
        return cellLoc.getLac();
    }

    public int getPsc() {
        return cellLoc.getPsc();
    }

}

在我的主要活动中,这是我初始化它的方式:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    //tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
    cell = new CellInformation();
}

我收到System services not available to Activities before onCreate() 错误。如果我不打算在 onCreate 中初始化它,那么我应该在哪里初始化它? 如果我的逻辑完全错误和/或这不是 Android 标准,我该如何解决?

【问题讨论】:

    标签: java android class android-activity extends


    【解决方案1】:

    在需要之前不要扩展 Activity。我看到了 CellInformation 类,其中不需要 Activity 类。删除它,它会解决你的问题。

    public class CellInformation  {
      ..... // Method and Attributes.
       private Context context;
    
       CellInformation(Context context) {
         this.context = context;
         tm = (TelephonyManager)this.context.getSystemService(Context.TELEPHONY_SERVICE);
       }
    }
    

    在 Activity 中使这个类的对象像:-

    cell = new CellInformation(this);
    

    现在,在您需要的活动中创建此类的对象,然后调用此CellInformation 的方法。

    【讨论】:

    • 在这种情况下,getSystemService 方法不起作用。这就是我扩展 Activity 的原因...
    • 我更新了答案并立即查看。当你制作这个类的对象时,将活动的上下文传递给CellInformation类的构造函数,并使用这个上下文调用context.getSystemService
    • 谢谢,但我的问题是关于使用扩展 Activity 的类,您的回答是告诉我不要扩展 Activity,这是解决非常具体问题的另一种方法。
    • CellInformation中没有使用扩展Activity类。你不应该扩展它
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-23
    • 2012-01-09
    相关资源
    最近更新 更多