当前位置: 移动技术网 > IT编程>移动开发>Android > Android的Service应用程序组件基本编写方法

Android的Service应用程序组件基本编写方法

2019年07月24日  | 移动技术网IT编程  | 我要评论

台湾hitfm,仇思隽,风华无双

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配置
复制代码 代码如下:

<service android:name=".firstservice"></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);
}
}

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网