服务开启的两种方式:
1.start开启服务
Intent intent = new Intent(Context, Service.class); //开启服务 startService(intent); //关闭服务 stopService(intent);
2.bind开启服务
Service.class:
public class MyService extends Service { private static final String TAG = "MyService"; public class MyBinder extends Binder{ public void callInService(){ inService(); } } private void inService() { Log.d(TAG, "inService: "); } @Nullable @Override public IBinder onBind(Intent intent) { return new MyBinder(); } @Override public void onCreate() { super.onCreate(); Log.d(TAG, "onCreate: "); } @Override public void onDestroy() { super.onDestroy(); Log.d(TAG, "onDestroy: "); } }
理解Service类: 首先写一个类继承Service,重写public IBinder onBind(Intent intent)方法,它的返回值是IBinder,可以跟Service的调用者交互.
在服务中还要写一个内部类继承Binder,在这个类里写一些方法,其方法体就是调用服务里的方法.
然后在onBind方法里return 我们刚写的类的实例.return new MyBinder();
在清单文件中注册服务.( 容易忘掉 )
MainActivity.class:
public class MainActivity extends AppCompatActivity { private static final String TAG = "MainActivity"; private MyService.MyBinder myBinder; private MyConn conn; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void btn_bind(View view){ Intent intent = new Intent(this, MyService.class); if(conn==null) { conn = new MyConn(); } bindService(intent,conn,BIND_AUTO_CREATE); } public void btn_call(View view){ myBinder.callInService(); } public void btn_unbind(View view){ if (conn!=null) { unbindService(conn); } } private class MyConn implements ServiceConnection{ @Override public void onServiceConnected(ComponentName name, IBinder service) { myBinder= (MyService.MyBinder) service; Log.d(TAG, "onServiceConnected: "); } @Override public void onServiceDisconnected(ComponentName name) { } } }
在activity中用bindService开启服务,此方法接受三个参数,第一个是intent,第二个是ServiceConnection,第三个是int类型,主要作用是绑定时是否自动创建Service,( 如果服务未创建 ).0代表不自动创建,BIND_AUTO_CREATE代表自动创建.
还要在activity里写一个内部类实现ServiceConnection接口,重写public void onServiceConnected(ComponentName name, IBinder service)和public void onServiceDisconnected(ComponentName name)方法.当服务连接和断开时调用这两个方法.
在public void onServiceConnected(ComponentName name, IBinder service)方法中把IBinder service转换成我们在服务中写的内部类.如 myBinder= (MyService.MyBinder) service;
这样就可以用myBinder调用服务里的方法了.如: myBinder.callInService();