Android的Service应用程序组件基本编写方法
程序员文章站
2023-12-04 11:20:40
service是什么 service是一个android 系统中的应用程序组件,它跟activity的级别差不多,但是他没有图形化界面,不能自己运行,只能后台运行,并且可以...
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);
}
}
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);
}
}