Android学习之Service服务

startService开启服务

startService(Intent) 通过这种方式开启的服务执行的生命周期方法:
第一次调用startService的时候
onCreate()->onStartCommand
再次调用startService
startService->onStartCommand
.
想停止用startService开启的服务 stropService(intent);
stopService执行之后Service会走onDestroy()方法,执行后Service销毁。
再次调用stopService没有反应。
.
如果在activity中通过startService方法开启一个服务,当activity退出的时候Service不会销毁,依然在后台运行,只有手动调用stopService或者应用管理器中关闭Service服务才会销毁。

startService开启服务示例

1.创建JAVA类 并继承Service服务

// 创建JAVA类 并继承Service服务
public class MyService extends Service{

	@Override
	public IBinder onBind(Intent arg0) {
		System.out.println("onBind!!!");
		return null;
	}
	@Override
	public void onCreate() {
		super.onCreate();
		System.out.println("onCreate!!!");
	}
	
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		System.out.println("onStartCommand!!!");
		return super.onStartCommand(intent, flags, startId);
		
	}
	
	@Override
	public void onDestroy() {
		System.out.println("onDestroy!!!");
		super.onDestroy();
	}

2.在程序清单中注册服务

 <service android:name="com.example.service.MyService"></service>

3.处理事件 开启服务或停止服务


public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
	}

	//开启服务
	public void start(View view) {
		Intent intent = new Intent(getApplicationContext(),MyService.class);
		startService(intent);
	}
	
	//停止服务
	public void stop(View view) {
		Intent intent = new Intent(getApplicationContext(),MyService.class);
		stopService(intent);
	}

	
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值