如何在Android中使用扩展Activity的类?

时间:2013-12-28 11:09:18

标签: java android class android-activity extends

我是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标准,我该如何解决?

1 个答案:

答案 0 :(得分:0)

只是在需要之前不要扩展活动。我看到了类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的方法。

相关问题