1. 程式人生 > >Service跨程序呼叫服務三部曲之AIDL詳解(三)

Service跨程序呼叫服務三部曲之AIDL詳解(三)

package com.example.client_aidl3_activity;

import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.example.aidl3.ICallback;
import com.example.aidl3.IService;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteException;

public class MainActivity extends Activity implements OnClickListener{

private IService mService;
private TextView tv;
private Button btBinder;
private String mResult;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv=(TextView) findViewById(R.id.tv);
btBinder=(Button) findViewById(R.id.bt_binder);
btBinder.setOnClickListener(this);

}

/**
     * service的回撥方法
     */
private ICallback.Stub mCallBack= new ICallback.Stub() {

@Override
public void showResult(int result) throws RemoteException {
// TODO Auto-generated method stub
Log.i("test", "showResult:"+result);
mResult=result+"";
//Message message=new Message();
//Message message=Message.obtain()避免分配新的物件,減少記憶體的開銷
Message message=Message.obtain();
message.what=0;
handler.sendMessage(message);

}
};

private  Handler handler=new Handler(){


@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case 0:
tv.setText("result"+mResult);
break;


default:
break;
}
}

};

@Override
     protected void onDestroy() {
         if(mService!=null){
            try {
                mService.unregisterCallback(mCallBack);
             } catch (RemoteException e) {
                 Log.e("TAG", "", e);
             }
         }
         //destroy的時候不要忘記unbindService
          unbindService(conn);
         super.onDestroy();
     }

private ServiceConnection conn= new ServiceConnection() {

@Override
public void onServiceDisconnected(ComponentName name) {
// TODO Auto-generated method stub
mService=null;
tv.setText("unconnect");
}

@Override
public void onServiceConnected(ComponentName name, IBinder service) {
// TODO Auto-generated method stub
mService=IService.Stub.asInterface(service);
try {
mService.registerCallback(mCallBack);
tv.setText("connect");
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.bt_binder:
Intent intent=new Intent();
intent.setAction("com.service3");
intent.setPackage("com.example.aidl3");
bindService(intent, conn, BIND_AUTO_CREATE);
Toast.makeText(this, "server 已連線", Toast.LENGTH_SHORT).show();
break;

}
}

}