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

时间:2023-12-17 04:22:00 

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);
}
}
标签:android,service
0
投稿

猜你喜欢

  • springboot整合mybatis-plus基于注解实现一对一(一对多)查询功能

    2021-06-16 13:08:29
  • Spring Boot中@Conditional注解介绍

    2022-03-03 15:23:37
  • C#将Json解析成DateTable的方法

    2022-11-19 20:10:42
  • Android常用的数据加密方式代码详解

    2022-07-24 14:30:06
  • C#验证给定字符串是否为数字的方法

    2021-08-24 10:22:21
  • 浅谈C#泛型的用处与特点

    2022-04-22 02:39:35
  • Java操作hdfs文件系统过程

    2023-12-13 23:42:32
  • Java中实现多线程关键词整理(总结)

    2023-09-08 16:08:49
  • 详解Java实现单例的五种方式

    2021-06-11 03:54:03
  • Java魔法堂之调用外部程序的方法

    2023-11-09 07:14:16
  • android实现点击按钮控制图片切换

    2022-10-16 02:38:55
  • C#实现简单打字小游戏

    2023-02-25 06:46:50
  • Dynamic和Var的区别及dynamic使用详解

    2022-09-22 13:18:23
  • spring是如何解析xml配置文件中的占位符

    2023-12-02 05:57:12
  • java.util.ArrayDeque类使用方法详解

    2022-12-13 11:19:02
  • Android 四种动画效果的调用实现代码

    2021-06-26 17:59:54
  • Android 手势 正则匹配图片实例代码

    2021-09-22 05:23:42
  • Mybatis步骤分解实现一个增删改查程序

    2021-09-16 01:12:43
  • 关于Lambda表达式的方法引用和构造器引用简的单示例

    2022-09-18 05:02:08
  • Android仿Keep运动休息倒计时圆形控件

    2022-08-02 07:54:36
  • asp之家 软件编程 m.aspxhome.com