1、遠程服務的類的建立
(1)服務類
public class MyService extends Service {
// 遠端服務
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return new MyBinder();
}
private class MyBinder extends IService.Stub{
@Override
public void CallMethodInService(String name) throws RemoteException {
sayHelloInservice(name);
}
}
public void sayHelloInservice(String name){
Looper.prepare();
Toast.makeText(this, "你好"+name, 1).show();
Looper.loop();
}
@Override
public void onCreate() {
System.out.println("reomte oncreate");
super.onCreate();
}
@Override
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
System.out.println("onstart");
super.onStart(intent, startId);
}
@Override
public void onDestroy() {
// TODO Auto-generated method stub
System.out.println("ondestroy");
super.onDestroy();
}
}
配置
<service android:name=".MyService" >
<intent-filter>
<action android:name="cn.itcast.remoteservice"/>
</intent-filter>
</service>
</application>
(2)介面IService.aidl
package cn.itcast.remoteservice;
interface IService {
void CallMethodInService(String name);
}
(3)自動產生的檔案IService.java
public interface IService extends android.os.IInterface
{
/** Local-side IPC implementation stub class. */
public static abstract class Stub extends android.os.Binder
implements remoteservice.IService
{
........................
}
工程結構圖
2、遠端存取端
DemoActivity.java類
public class DemoActivity extends Activity {
Intent intent;
MyRemoteConn conn;
cn.itcast.remoteservice.IService iRemoteService;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
conn = new MyRemoteConn();
}
private class MyRemoteConn implements ServiceConnection{
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
iRemoteService = cn.itcast.remoteservice.IService.Stub.asInterface(service);
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
}
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
unbindService(conn);
super.onDestroy();
}
//綁定按鈕
public void bindRemoteService(View view){
Intent service = new Intent();
service.setAction("cn.itcast.remoteservice");
bindService(service,new MyRemoteConn() , BIND_AUTO_CREATE);
}
//執行服務方法
public void callMethodInRemoteService(View view){
try {
iRemoteService.CallMethodInService("遠程張三 ");
} catch (RemoteException e) {
e.printStackTrace();
}
}
}
(2)介面IService.aidl
package cn.itcast.remoteservice;
interface IService {
void CallMethodInService(String name);
}
(3)自動產生的檔案IService.java
public interface IService extends android.os.IInterface
{
/** Local-side IPC implementation stub class. */
public static abstract class Stub extends android.os.Binder
implements remoteservice.IService
{
........................
}
工程檔案結構