1.写一个类继承 Service
public class MyService extends Service {
public MyService() {
Log.e("TAG", "MyService()");
}
@Override
public void onCreate() {
super.onCreate();
Log.e("TAG", "MyService onCreate()");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e("TAG", "MyService onStartCommand()");
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
super.onDestroy();
Log.e("TAG", "MyService onDestroy()");
}
@Override
public IBinder onBind(Intent intent) {
Log.e("TAG", "onBind()");
return new Binder();
}
@Override
public boolean onUnbind(Intent intent) {
Log.e("TAG", "onUnbind()");
return super.onUnbind(intent);
}
}
2.在androidManifest.xml里配置
<service android:name="com.atguigu.l07_service.local.MyService"/>
3、有两种方式启动
用第一种方式启动与停止:
public void startMyService(View v) {
Intent intent = new Intent(this, MyService.class);
startService(intent);
Toast.makeText(this, "start service", Toast.LENGTH_SHORT).show();
}
public void stopMyService(View v) {
Intent intent = new Intent(this, MyService.class);
stopService(intent);
Toast.makeText(this, "stop service", Toast.LENGTH_SHORT).show();
}
也可以用第二种方式调用
public void bindMyService(View v) {
Intent intent = new Intent(this, MyService.class);
//创建连接对象
if(conn==null) {
conn = new ServiceConnection() {
@Override
public void onServiceDisconnected(ComponentName name) {
Log.e("TAG", "onServiceDisconnected()");
}
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
Log.e("TAG", "onServiceConnected()");
}
};
//绑定Service
bindService(intent, conn, Context.BIND_AUTO_CREATE);
Toast.makeText(this, "bind service", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "已经bindservice", Toast.LENGTH_SHORT).show();
}
}
//解绑服务
public void unbindMyService(View v) {
if(conn!=null) {
unbindService(conn);
conn = null;
Toast.makeText(this, "unbind service", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "还没有bindservice", Toast.LENGTH_SHORT).show();
}
}
退出activity的时候释放资源
//在Activity死亡之前调用
@Override
protected void onDestroy() {
super.onDestroy();
if(conn!=null) {
unbindService(conn);
conn = null;
}
}
否则退出APP时会出现如下错误
生命周期
注意:
a、所有activity 断开是才调用onUnbind