无法获取服务对象(onServiceConnected 从未调用)

发布于 2024-11-07 04:26:25 字数 4320 浏览 0 评论 0原文

我尝试为 Android 上的电话状态编写 XML 日志。首先,我编写了一个类来在活动处于活动状态时记录事件。现在我尝试在服务中编写 xml 文件并将服务绑定到活动。稍后我想在后台记录状态,所以我至少需要一项服务和一个广播接收器。但我绑定失败,无法通过 onServiceConnected() 方法获取服务对象。该方法从未被调用。我尝试等待服务的异步启动,就像我在另一篇文章中读到的那样,但它不起作用。 我使用 eclipse 和普通的调试器。

public class MyActivity extends Activity {
//The layout of the application.
private TableLayout t;
//The service, which is writing the xml-file.
private FileService fservice;
private boolean mIsBound;
private final Handler handler = new Handler(); 

private ServiceConnection mConnection = new ServiceConnection() {
    public void onServiceConnected(ComponentName className, IBinder service) {
        // This is called when the connection with the service has been
        // established, giving us the service object we can use to
        // interact with the service.  Because we have bound to a explicit
        // service that we know is running in our own process, we can
        // cast its IBinder to a concrete class and directly access it.
        fservice = ((FileService.LocalBinder)service).getService();

    }

    public void onServiceDisconnected(ComponentName className) {
        // This is called when the connection with the service has been
        // unexpectedly disconnected -- that is, its process crashed.
        // Because it is running in our same process, we should never
        // see this happen.
        fservice = null;
    }
};

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.table_layout);

    doBindService();

    //Initialization of the TableLayout. 
    t = (TableLayout) findViewById(R.id.myTableLayout);
}

@Override
public void onStart(){
    super.onStart();

    //Initialization of the TelephonyManager.
    final TelephonyManager myTelephonyMgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);

    Runnable r = new Runnable()
    {
            public void run()
            {
                //Gets the IMSI and IMEI.
                String imsi = myTelephonyMgr.getSubscriberId();
                createRow(getTimeStamp(), "IMSI: "+imsi);
                createLine();
                String imei = myTelephonyMgr.getDeviceId();
                createRow(getTimeStamp(), "IMEI: "+imei);
                createLine();

                //Gets the cell informations.
                GsmCellLocation cell = (GsmCellLocation) myTelephonyMgr.getCellLocation();
                createRow(getTimeStamp(),"CID: "+cell.getCid());
                createLine();
                createRow(getTimeStamp(), "LAC: "+cell.getLac());
                createLine();

                //Gets the call states.
                myTelephonyMgr.listen(new MyPhoneStateListener(MyActivity.this), PhoneStateListener.LISTEN_CALL_STATE);
            }
    };

    handler.postDelayed(r, 4000);


}

/**
 * Creates a new TableRow.
 * 
 * @param stampText
 * @param actionText
 */
protected void createRow(String stampText, String actionText){
    ...
    fservice.createRow(stampText, actionText);
}

...


private void doBindService() {
    // Establish a connection with the service.  We use an explicit
    // class name because we want a specific service implementation that
    // we know will be running in our own process (and thus won't be
    // supporting component replacement by other applications).
    bindService(new Intent(MyActivity.this, FileService.class), mConnection, Context.BIND_AUTO_CREATE);
    mIsBound = true;
}

private void doUnbindService() {
    if (mIsBound) {
        // Detach our existing connection.
        unbindService(mConnection);
        mIsBound = false;
    }
}


@Override
protected void onDestroy() {
    super.onDestroy();
    doUnbindService();
} 

}

公共类 FileService 扩展服务{ ... // 这是接收来自客户端的交互的对象。 私有最终 IBinder mBinder = new LocalBinder();

/**
 * Class for clients to access.  Because we know this service always
 * runs in the same process as its clients, we don't need to deal with
 * IPC.
 */
public class LocalBinder extends Binder {
    FileService getService() {
        return FileService.this;
    }
}

@Override
public IBinder onBind(Intent intent) {
    return mBinder;

}
...

}

I try to write a XML-log for phonestates on android. First i wrote a a single class to log things while the activity is active. Now i tried to write the xml-file in a service an bind the service to the activity. Later i want to log the states in background, so i will need at least one service and a broadcast reciever. But i fail at the binding and can't get a service object back at the onServiceConnected() - method. The method is never called. I tried to wait for the asynchronous start up of the service, like i read in another post, but it didn't work.
I work with eclipse and the normal debugger.

public class MyActivity extends Activity {
//The layout of the application.
private TableLayout t;
//The service, which is writing the xml-file.
private FileService fservice;
private boolean mIsBound;
private final Handler handler = new Handler(); 

private ServiceConnection mConnection = new ServiceConnection() {
    public void onServiceConnected(ComponentName className, IBinder service) {
        // This is called when the connection with the service has been
        // established, giving us the service object we can use to
        // interact with the service.  Because we have bound to a explicit
        // service that we know is running in our own process, we can
        // cast its IBinder to a concrete class and directly access it.
        fservice = ((FileService.LocalBinder)service).getService();

    }

    public void onServiceDisconnected(ComponentName className) {
        // This is called when the connection with the service has been
        // unexpectedly disconnected -- that is, its process crashed.
        // Because it is running in our same process, we should never
        // see this happen.
        fservice = null;
    }
};

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.table_layout);

    doBindService();

    //Initialization of the TableLayout. 
    t = (TableLayout) findViewById(R.id.myTableLayout);
}

@Override
public void onStart(){
    super.onStart();

    //Initialization of the TelephonyManager.
    final TelephonyManager myTelephonyMgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);

    Runnable r = new Runnable()
    {
            public void run()
            {
                //Gets the IMSI and IMEI.
                String imsi = myTelephonyMgr.getSubscriberId();
                createRow(getTimeStamp(), "IMSI: "+imsi);
                createLine();
                String imei = myTelephonyMgr.getDeviceId();
                createRow(getTimeStamp(), "IMEI: "+imei);
                createLine();

                //Gets the cell informations.
                GsmCellLocation cell = (GsmCellLocation) myTelephonyMgr.getCellLocation();
                createRow(getTimeStamp(),"CID: "+cell.getCid());
                createLine();
                createRow(getTimeStamp(), "LAC: "+cell.getLac());
                createLine();

                //Gets the call states.
                myTelephonyMgr.listen(new MyPhoneStateListener(MyActivity.this), PhoneStateListener.LISTEN_CALL_STATE);
            }
    };

    handler.postDelayed(r, 4000);


}

/**
 * Creates a new TableRow.
 * 
 * @param stampText
 * @param actionText
 */
protected void createRow(String stampText, String actionText){
    ...
    fservice.createRow(stampText, actionText);
}

...


private void doBindService() {
    // Establish a connection with the service.  We use an explicit
    // class name because we want a specific service implementation that
    // we know will be running in our own process (and thus won't be
    // supporting component replacement by other applications).
    bindService(new Intent(MyActivity.this, FileService.class), mConnection, Context.BIND_AUTO_CREATE);
    mIsBound = true;
}

private void doUnbindService() {
    if (mIsBound) {
        // Detach our existing connection.
        unbindService(mConnection);
        mIsBound = false;
    }
}


@Override
protected void onDestroy() {
    super.onDestroy();
    doUnbindService();
} 

}

public class FileService extends Service{
...
// This is the object that receives interactions from clients.
private final IBinder mBinder = new LocalBinder();

/**
 * Class for clients to access.  Because we know this service always
 * runs in the same process as its clients, we don't need to deal with
 * IPC.
 */
public class LocalBinder extends Binder {
    FileService getService() {
        return FileService.this;
    }
}

@Override
public IBinder onBind(Intent intent) {
    return mBinder;

}
...

}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

萌梦深 2024-11-14 04:26:25

您是否将服务定义添加到 AndroidManifest.xml 文件中?就像这样:

<manifest ... >
  ...
  <application ... >
      <service android:name=".ExampleService" />
      ...
  </application>
</manifest>

Did you add the Service definition to the AndroidManifest.xml file? Like so:

<manifest ... >
  ...
  <application ... >
      <service android:name=".ExampleService" />
      ...
  </application>
</manifest>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文