zoukankan      html  css  js  c++  java
  • 服务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);
            }
        }
    }
    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);
            }
        }
    
    }
    public interface IStundent {
        public String queryStudent(int no);
    }

     

  • 相关阅读:
    shiro3
    shiro2
    shiro1
    Android设计模式之策略模式
    Notify通知
    Menu菜单
    Windows下配置cygwin和ndk编译环境
    Android组件化和插件化开发
    android MVP模式介绍与实战
    实现LoaderCallbacks接口动态循环加载网上图片并展示在手机屏幕上 ...
  • 原文地址:https://www.cnblogs.com/heml/p/3515355.html
Copyright © 2011-2022 走看看