//一、服务创建
public MyService extends Service { public Myservice(){} //默认的构造方法 public IBinder onBind( Intent intent ){}//用于绑定服务}
//二、服务的两种启动方式
- //1.startService方式启动
- //2.bindService方式启动
//1.startService方式启动
public class MyService extends Service{ public IBinder onBind(Intent intent){return null;}/*1*/ public void onCreate(){super.onCreate();}/*2*/ public int onStartCommand(Intent intent, int flags, int startId){ return super.onStartCommand(intent, flags, startId); }/*3*/ public void onDestroy(){super.onDestroy();}}
public MainActivity extends AppCompatActivity{ public void onCreate(Bundle savedInstanceState){/*定义按钮*/ Button start = (Button)findViewById(R.id.btn_start); Button stop = (Button)findViewById(R.id.btn_stop); }/*定义开启和关闭服务方法*/ public start(View view){ Intent intent = new Intent(this, MyService.class); startService(intent); } public stop(View view){ Intent intent = new Intent(this, MyService.class); stopService(intent); }}
//2.bindService方式启动
public class MyService extends Service{/*创建服务代理MyBinder,用于调用服务中的方法*/ class MyBinder extends Binder { public void callMethodInService(){//调用服务中方法的方法 methodInService(); } }/*1*/public void onCreate(){super.onCreate();} //第一次创建服务执行/*2*/public IBinder onBind(Intent intent){return new MyBinder();} //绑定服务,用于启动服务 public void methodInService(){} //一个自定义方法,代表执行服务中的方法/*3*/public boolean onUnBind(Intent intent){ return super.onUnBind(intent); //解绑服务 }}
public class MainActivity extends AppCompatActivity{ private MyService.MyBinder myBinder; //声明服务代理,用于调用服务中的方法 private MyConn myconn; //声明连接监听器,用于实现监听服务链接的状态 private class MyConn implements ServiceConnection{ public void onServiceConnected(ComponentName name, IBinder service){ //成功绑定服务时调用,返回服务代理对象 myBinder = (MyService.MyBinder)service; } public void onServiceDisconnected(ComponentName name){} //服务失去连接时调用 } public void onCreate(..){..} //绑定服务 public void btnBind(View view){ //方法名是按钮的click名 if(myconn==null){ myconn = new MyConn(); } Intent intent = new Intent(this, MyService.class); bindService(intent, myconn, BIND_AUTO_CREATE); //参1,参2链接对象,参3代表服务不存在就创建 } //解绑服务 public void btnUnBind(View view){ if(myconn != null){ unbindService(myconn);//解绑服务 myconn = null; } } //调用服务中方法的方法 public void btnCall(View view){ myBinder.callMethodInService(); }}