android中service方法,Android的Service基本编写方法

Service是什么

Service是一个android 系统中的应用程序组件,它跟Activity的级别差不多,但是他没有图形化界面,不能自己运行,只能后台运行,并且可以和其他组件进行交互如更新ContentProvider,Intent以及系统的通知等等。其启动方式有两种:context.startService() 和 context.bindService()。Service通常用来处理一些耗时比较长的操作。

Service的编写:

创建一个类(这里为FirstService)继承android.app.Service,并覆盖以下方法: onBind(Intent intent) Return the communication channel to the service. onCreate() Called by the system when the service is first created. onStartCommand(Intent intent, int flags, int startId) Called by the system every time a client explicitly starts the service by calling startService(Intent), providing the arguments it supplied and a unique integer token representing the start request. onDestroy() Called by the system to notify a Service that it is no longer used and is being removed. AndroidManifest.xml文件中添加service配置:

在Activity中启动和停止Service的点击事件的编写

class StartServiceListener implements OnClickListener {

@Override

public void onClick(View v) {

Intent intent = new Intent();

intent.setClass(TestActivity.this, FirstService.class);

startService(intent);

}

}

class StopServiceListener implements OnClickListener {

@Override

public void onClick(View v) {

Intent intent = new Intent();

intent.setClass(TestActivity.this, FirstService.class);

stopService(intent);

}

}

(特别说明:本文部分内容是在观看marschen的Android视频教程时做的笔记,感谢marschen推出的视频教程,这里也推荐给大家:http://www.marschen.com/portal.php)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值