Androidk开发入门之使用AIDL实现进程通信

远程服务端:

StudentService:

package cn.leigo.remote.service;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;
import cn.leigo.aidl.StudentQuery;

public class StudentService extends Service {
	private IBinder binder = new StudentQueryBinder();
	private String[] names = { "张三", "李四", "王五" };
	
	public String queryStudentByNo(int no) {
		if (no > 0 && no < 4) {
			return names[no - 1];
		}
		return null;
	}

	@Override
	public IBinder onBind(Intent intent) {
		return binder;
	}
	
	private final class StudentQueryBinder extends StudentQuery.Stub {

		@Override
		public String queryStudent(int number) throws RemoteException {
			return queryStudentByNo(number);
		}
	}

}

package cn.leigo.aidl;

interface StudentQuery {
	String queryStudent(int number);
}

访问者:

package cn.leigo.remoteserviceclient;

import cn.leigo.aidl.StudentQuery;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends Activity implements OnClickListener {
	private EditText mStudentNoEditText;
	private Button mQueryButton;
	private TextView mResultTextView;
	private ServiceConnection conn = new StudentServiceConnection();
	private StudentQuery studentQuery;

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

		mStudentNoEditText = (EditText) findViewById(R.id.et_student_no);
		mQueryButton = (Button) findViewById(R.id.btn_query);
		mResultTextView = (TextView) findViewById(R.id.tv_result);
		mQueryButton.setOnClickListener(this);

		Intent service = new Intent("cn.leigo.query");
		bindService(service, conn, BIND_AUTO_CREATE);
	}

	private class StudentServiceConnection implements ServiceConnection {

		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			studentQuery = StudentQuery.Stub.asInterface(service);
		}

		@Override
		public void onServiceDisconnected(ComponentName name) {
			studentQuery = null;
		}

	}

	@Override
	public void onClick(View v) {
		int number = Integer.parseInt(mStudentNoEditText.getText().toString());
		String name = "";
		try {
			name = studentQuery.queryStudent(number);
		} catch (RemoteException e) {
			e.printStackTrace();
		}
		mResultTextView.setText(name);

	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		unbindService(conn);
	}

}


你可能感兴趣的:(android,service,aidl)