服务bindService()方法启动服务

服务bindService()方法启动服务
public class MainActivity extends Activity {
    private EditText studentno;
    private ServiceConnection conn = new StudentServiceConnection();
    private IStundent iStundent;
    private TextView resultView;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        resultView = (TextView) this.findViewById(R.id.resultView);
        studentno = (EditText) this.findViewById(R.id.studentno);
        Button button = (Button) this.findViewById(R.id.button);
        button.setOnClickListener(new ButtonClickListener());
        Intent service = new Intent(this, StudentService.class);
        bindService(service, conn, BIND_AUTO_CREATE);
    }
    
    private class StudentServiceConnection implements ServiceConnection{
        public void onServiceConnected(ComponentName name, IBinder service) {
            iStundent = (IStundent)service;
        }
        public void onServiceDisconnected(ComponentName name) {
            iStundent = null;
        }
    }
    
    @Override
    protected void onDestroy() {
        unbindService(conn);
        super.onDestroy();
    }

    private final class ButtonClickListener implements View.OnClickListener{
        public void onClick(View v) {
            String no = studentno.getText().toString();
            String name = iStundent.queryStudent(Integer.valueOf(no));
            resultView.setText(name);
        }
    }
}
服务bindService()方法启动服务
服务bindService()方法启动服务
public class StudentService extends Service{
    private String[] names = {"张飞","李小龙","赵薇"};
    private IBinder binder = new StundentBinder();
    
    public String query(int no){
        if(no>0 && no<4){
            return names[no - 1];
        }
        return null;
    }
    
    @Override
    public IBinder onBind(Intent intent) {
        return binder;
    }
    
    private class StundentBinder extends Binder implements IStundent{
        public String queryStudent(int no) {
            return query(no);
        }
    }

}
服务bindService()方法启动服务
public interface IStundent {
    public String queryStudent(int no);
}

 服务bindService()方法启动服务

服务bindService()方法启动服务

服务bindService()方法启动服务

服务bindService()方法启动服务

上一篇:IOS6、IOS7导航栏适配问题


下一篇:前端MVVM学习之KnockOut(二)