//一、服务创建

  1. public MyService extends Service {
  2. public Myservice(){} //默认的构造方法
  3. public IBinder onBind( Intent intent ){}//用于绑定服务
  4. }

//二、服务的两种启动方式

  • //1.startService方式启动
  • //2.bindService方式启动

//1.startService方式启动

  1. public class MyService extends Service{
  2. public IBinder onBind(Intent intent){return null;}
  3. /*1*/ public void onCreate(){super.onCreate();}
  4. /*2*/ public int onStartCommand(Intent intent, int flags, int startId){
  5. return super.onStartCommand(intent, flags, startId);
  6. }
  7. /*3*/ public void onDestroy(){super.onDestroy();}
  8. }
  1. public MainActivity extends AppCompatActivity{
  2. public void onCreate(Bundle savedInstanceState){
  3. /*定义按钮*/
  4. Button start = (Button)findViewById(R.id.btn_start);
  5. Button stop = (Button)findViewById(R.id.btn_stop);
  6. }
  7. /*定义开启和关闭服务方法*/
  8. public start(View view){
  9. Intent intent = new Intent(this, MyService.class);
  10. startService(intent);
  11. }
  12. public stop(View view){
  13. Intent intent = new Intent(this, MyService.class);
  14. stopService(intent);
  15. }
  16. }

//2.bindService方式启动

  1. public class MyService extends Service{
  2. /*创建服务代理MyBinder,用于调用服务中的方法*/
  3. class MyBinder extends Binder {
  4. public void callMethodInService(){//调用服务中方法的方法
  5. methodInService();
  6. }
  7. }
  8. /*1*/public void onCreate(){super.onCreate();}
  9. //第一次创建服务执行
  10. /*2*/public IBinder onBind(Intent intent){return new MyBinder();}
  11. //绑定服务,用于启动服务
  12. public void methodInService(){}
  13. //一个自定义方法,代表执行服务中的方法
  14. /*3*/public boolean onUnBind(Intent intent){
  15. return super.onUnBind(intent); //解绑服务
  16. }
  17. }
  1. public class MainActivity extends AppCompatActivity{
  2. private MyService.MyBinder myBinder;
  3. //声明服务代理,用于调用服务中的方法
  4. private MyConn myconn;
  5. //声明连接监听器,用于实现监听服务链接的状态
  6. private class MyConn implements ServiceConnection{
  7. public void onServiceConnected(ComponentName name, IBinder service){
  8. //成功绑定服务时调用,返回服务代理对象
  9. myBinder = (MyService.MyBinder)service;
  10. }
  11. public void onServiceDisconnected(ComponentName name){}
  12. //服务失去连接时调用
  13. }
  14. public void onCreate(..){..}
  15. //绑定服务
  16. public void btnBind(View view){ //方法名是按钮的click名
  17. if(myconn==null){ myconn = new MyConn(); }
  18. Intent intent = new Intent(this, MyService.class);
  19. bindService(intent, myconn, BIND_AUTO_CREATE);
  20. //参1,参2链接对象,参3代表服务不存在就创建
  21. }
  22. //解绑服务
  23. public void btnUnBind(View view){
  24. if(myconn != null){
  25. unbindService(myconn);//解绑服务
  26. myconn = null;
  27. }
  28. }
  29. //调用服务中方法的方法
  30. public void btnCall(View view){
  31. myBinder.callMethodInService();
  32. }
  33. }