本地service(L07_service)

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

qq_27662081

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值