查询学号的简单例子

交互图


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);}


更多相关文章

  1. Android(安卓)相机实例(一)
  2. Flutter知识点:数据存储之File
  3. android 用代码编写linearlayout布局
  4. Android实现应用下载并自动安装apk包
  5. 编写android拨打电话apk应用实例代码
  6. android计算器简单版【安卓进化一】
  7. Android: 自定义Tab样式
  8. android手势翻页效果
  9. Android(安卓)Studio学习之对文件的基本了解

随机推荐

  1. Android(安卓)jni编程浅入深出之-- 与原
  2. android 显示内容被底部导航栏遮挡
  3. android真机调试步骤
  4. 翻翻git之---一个丰富的通知工具类 Notif
  5. 快速生成移动设备应用图标的在线工具 - m
  6. Android(安卓)NDK开发“Hello World NDK
  7. Google 官方:对 Android(安卓)手机硬件菜
  8. android app --- 快速集成SMS实现短信验
  9. 关于安卓活动的生命周期
  10. Android(安卓)自定义view仿IOS开关