远程服务的调用步骤

1\ 编写service接口

2\ 把IService接口中的 public \ private 去掉, 把文件扩展名更改为 aidl


package com.gyarmy.service01;

 interface IService {
	
	 void callServiceMethod();
	
}


3\ 把MyAgent的继承更改为 IService的 Stub

package com.gyarmy.service01;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;

public class MyService extends Service {

	private class MyAgent extends IService.Stub{
		@Override
		public void callServiceMethod() {
			// TODO Auto-generated method stub
			serviceMethod();
		}

		
	}
	
	
	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		
		System.out.println("绑定服务被调用");
		
		return new MyAgent();
	}
	
	@Override
	public void onStart(Intent intent, int startId) {
		// TODO Auto-generated method stub
		
		System.out.println("开启服务被调用");
		
		super.onStart(intent, startId);
	}
	
	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		
		System.out.println("关闭服务");
		super.onDestroy();
	}
	
	public void serviceMethod(){
		System.out.println("www.gyarmy.com");
	}
	

}

4\ 内线类的方法, 调用服务的方法


5\ 编写本地的 bindservice


6\编写 myconnection


package com.gyarmy.service02;

import com.gyarmy.service01.IService;

import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.view.Menu;
import android.view.View;

public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}
	
	private IService agent;
	
	public void callRemoteService(View v){
		Intent intent = new Intent();
		intent.setAction("com.gyarmy.rms");
		bindService(intent, new MyConn(), BIND_AUTO_CREATE);
	}
	
	public class MyConn implements ServiceConnection{

		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			// TODO Auto-generated method stub
			//agent = (IService.Stub)service;
			agent = IService.Stub.asInterface(service);
		}

		@Override
		public void onServiceDisconnected(ComponentName name) {
			// TODO Auto-generated method stub
			
		}
		
		
	}
	
	public void callRemoteMethod(View v) throws RemoteException{
		
		agent.callServiceMethod();
	}

}


7\ 调用服务中的方法

原文链接: 远程服务的调用步骤 版权所有,转载时请注明出处,违者必究。
注明出处格式:流沙团 ( https://gyarmy.com/post-136.html )

发表评论

0则评论给“远程服务的调用步骤”