在初始化类成员之前调用方法

时间:2014-01-21 07:53:45

标签: java android android-intent android-service

我在android中使用服务时遇到错误。我调用了一个活动CallingScreenActivity,我通过意图调用它并输入一个数字字符串给我打电话。 所以我在CallingScreenActivity中所做的就是首先初始化像这样的类成员

 private boolean serviceConnected = false;
  private ISipService service;
  private ServiceConnection connection = new ServiceConnection() {

      @Override
      public void onServiceConnected(ComponentName arg0, IBinder arg1) {
          service = ISipService.Stub.asInterface(arg1);
          try {
              // Log.d(THIS_FILE,
              // "Service started get real call info "+callInfo.getCallId());
              Log.e("onservice connected", "on service  connected");
              serviceConnected = true;

          } catch (Exception e) {
              e.printStackTrace();
          }
      }

      @Override
      public void onServiceDisconnected(ComponentName arg0) {
          Log.e("service disconnected", "desconnected service ");
          serviceConnected = false;
      }
  };

然后我在onCreate()中绑定服务,如下所示:

 bindService(new Intent(this, SipService.class), connection, Context.BIND_AUTO_CREATE);

最后从意图中获取数字并调用方法:

  private void placeCallWithOption(String number) {
      if (service == null) {
          Log.e("servcie is null ", "service is null");
          return;
      }

      try {
          service.makeCallWithOptions(num, 1, null);
      } catch (RemoteException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
      }
  }

现在我的问题是,每当我调用此活动进行调用时,它首先调用方法placeCallWithoutOption并稍后连接服务,以便每次在方法中打印 service is null 并返回服务已连接在服务连接方法中。 我应该怎样管理这个请帮助..

2 个答案:

答案 0 :(得分:1)

在连接之前,您无法从服务中调用任何方法。所以,你可以:

1)在活动开始时添加进度对话框“连接服务...”

2)连接服务后隐藏进度对话框,并从onServiceConnected()调用placeCallWithOption()(不早)。

答案 1 :(得分:1)

placeCallWithOption内调用此函数onServiceConnected

在活动中创建变量:

private String number;

和活动的onCreate

number=getIntent().getStringExtra("<number_key>",null);

并在onServiceConnected

 @Override
  public void onServiceConnected(ComponentName arg0, IBinder arg1) {
      service = ISipService.Stub.asInterface(arg1);
      try {
          placeCallWithOption(number);
          // Log.d(THIS_FILE,
          // "Service started get real call info "+callInfo.getCallId());
          Log.e("onservice connected", "on service  connected");
          serviceConnected = true;

      } catch (Exception e) {
          e.printStackTrace();
      }
  }