Android中和service进行本地通讯
16lz
2022-05-24
查询学号的简单例子
交互图
service代码
package cn.wonder.studertno;import android.app.Service;import android.content.Intent;import android.os.Binder;import android.os.IBinder;/** * 服务代码 * @author Administrator * */public class StudentService extends Service{private String[] names = {"张三","李四","王五","赵六","钱七"};private IBinder iBinder = new StudentBinder();public String query(int no) {if(no>0 && no<6) {return names[no-1];}else {return "只能查询学号1-5的学生";}}@Overridepublic IBinder onBind(Intent intent) {return iBinder;}//此为私有private class StudentBinder extends Binder implements IStudent{@Overridepublic String queryStudent(int no) {return query(no);}}}
Main代码
package cn.wonder.studertno;import android.content.ComponentName;import android.content.Intent;import android.content.ServiceConnection;import android.os.Bundle;import android.os.IBinder;import android.support.v7.app.ActionBarActivity;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.TextView;//客户端public class MainActivity extends ActionBarActivity {private EditText studentno;private StudentServiceConnection conn = new StudentServiceConnection();private IStudent iStudent;private TextView resultView;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);resultView = (TextView) findViewById(R.id.export);studentno = (EditText) findViewById(R.id.studentno);Button button = (Button) findViewById(R.id.button);button.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {//得到输入的学号String no = studentno.getText().toString();String name = iStudent.queryStudent(Integer.parseInt(no));resultView.setText(name);}});/* * 激活服务(显示激活) */Intent service = new Intent(this, StudentService.class);//BIND_AUTO_CREATE绑定自动创建bindService(service, conn, BIND_AUTO_CREATE);}private class StudentServiceConnection implements ServiceConnection {@Overridepublic void onServiceConnected(ComponentName name, IBinder service) {iStudent = (IStudent) service;}@Overridepublic void onServiceDisconnected(ComponentName name) {iStudent = null;}}@Overrideprotected void onDestroy() {unbindService(conn);super.onDestroy();}}
一个接口
package cn.wonder.studertno;public interface IStudent {public String queryStudent(int no);}
更多相关文章
- Android(安卓)相机实例(一)
- Flutter知识点:数据存储之File
- android 用代码编写linearlayout布局
- Android实现应用下载并自动安装apk包
- 编写android拨打电话apk应用实例代码
- android计算器简单版【安卓进化一】
- Android: 自定义Tab样式
- android手势翻页效果
- Android(安卓)Studio学习之对文件的基本了解