返回顶部

收藏

Android 的 Remote Service 开发实例

更多

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

[Java]代码

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,SDK

收藏

0人收藏

支持

0

反对

0

发表评论