Android 的 Remote Service 开发实例

RemoteService.zip 服务端
RemoteServiceClient.zip 客户端

private void startService(){
     if (started) {
       Toast.makeText(RemoteServiceClient.this, "Service already started", Toast.LENGTH_SHORT).show();
     } else {
       Intent i = new Intent();
       i.setClassName("com.collabera.labs.sai", "com.collabera.labs.sai.RemoteService");
       startService(i);
       started = true;
       updateServiceStatus();
       Log.d( getClass().getSimpleName(), "startService()" );
      }
                
  }

private void bindService() {
     if(conn == null) {
        conn = new RemoteServiceConnection();
        Intent i = new Intent();
        i.setClassName("com.collabera.labs.sai", "com.collabera.labs.sai.RemoteService");
        bindService(i, conn, Context.BIND_AUTO_CREATE);
        updateServiceStatus();
        Log.d( getClass().getSimpleName(), "bindService()" );
     } else {
       Toast.makeText(RemoteServiceClient.this, "Cannot bind - service already bound", Toast.LENGTH_SHORT).show();
     }
}

private void invokeService() {
     if(conn == null) {
        Toast.makeText(RemoteServiceClient.this, "Cannot invoke - service not bound", Toast.LENGTH_SHORT).show();
     } else {
        try {
            int counter = remoteService.getCounter();
            TextView t = (TextView)findViewById(R.id.notApplicable);
            t.setText( "Counter value: "+Integer.toString( counter ) );
            Log.d( getClass().getSimpleName(), "invokeService()" );
        } catch (RemoteException re) {
            Log.e( getClass().getSimpleName(), "RemoteException" );
        }
     }
}    

private void releaseService() {
      if(conn != null) {
            unbindService(conn);
            conn = null;
            updateServiceStatus();
            Log.d( getClass().getSimpleName(), "releaseService()" );
      } else {
            Toast.makeText(RemoteServiceClient.this, "Cannot unbind - service not bound", Toast.LENGTH_SHORT).show();
      }
}


private void stopService() {
      if (!started) {
            Toast.makeText(RemoteServiceClient.this, "Service not yet started", Toast.LENGTH_SHORT).show();
      } else {
            Intent i = new Intent();
            i.setClassName("com.collabera.labs.sai", "com.collabera.labs.sai.RemoteService");
            stopService(i);
            started = false;
            updateServiceStatus();
            Log.d( getClass().getSimpleName(), "stopService()" );
      }
}

Android 的 Remote Service 开发实例代码下载

具体下载目录在 /2011年资料/Android入门教程/Android 的 Remote Service 开发实例/

相关推荐