Android四大组件之一服务
概念
Service是Android系统中的四大组件之一,它是一种长生命周期的,没有可视化界面,运行于后台的一种服务程序。
A started service
被开启的service通过其他组件调用startService()被创建。
这种service可以无限地运行下去,必须调用stopSelf()方法或者其他组件调用stopService()方法来停止它。
当service被停止时,系统会销毁它。
A bound service
被绑定的service是当其他组件(一个客户)调用bindService()来创建的。
客户可以通过一个IBinder接口和service进行通信。
客户可以通过unbindService()方法来关闭这种连接。
一个service可以同时和多个客户绑定,当多个客户都解除绑定之后,系统会销毁service。
代码
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:orientation="vertical"android:layout_width="match_parent"android:layout_height="match_parent"><Buttonandroid:id="@+id/start_service"android:layout_width="match_parent"android:layout_height="wrap_content"android:text="Start Service" /><Buttonandroid:id="@+id/stop_service"android:layout_width="match_parent"android:layout_height="wrap_content"android:text="Stop Service" /><Buttonandroid:id="@+id/bind_service"android:layout_width="match_parent"android:layout_height="wrap_content"android:text="Bind Service" /><Buttonandroid:id="@+id/unbind_service"android:layout_width="match_parent"android:layout_height="wrap_content"android:text="Unbind Service" /><Buttonandroid:id="@+id/start_intent_service"android:layout_width="match_parent"android:layout_height="wrap_content"android:text="Start IntentService" /></LinearLayout>
package com.example.servicetest;import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;public class MainActivity extends AppCompatActivity implements View.OnClickListener{private MyService.DownloadBinder downloadBinder;private ServiceConnection connection = new ServiceConnection() {@Overridepublic void onServiceDisconnected(ComponentName name) {}@Overridepublic void onServiceConnected(ComponentName name, IBinder service) {downloadBinder = (MyService.DownloadBinder) service;downloadBinder.startDownload();downloadBinder.getProgress();}};@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);Button startService = (Button) findViewById(R.id.start_service);Button stopService = (Button) findViewById(R.id.stop_service);startService.setOnClickListener(this);stopService.setOnClickListener(this);Button bindService = (Button) findViewById(R.id.bind_service);Button unbindService = (Button) findViewById(R.id.unbind_service);bindService.setOnClickListener(this);unbindService.setOnClickListener(this);Button startIntentService = (Button) findViewById(R.id.start_intent_service);startIntentService.setOnClickListener(this);}
//点击的事件@Overridepublic void onClick(View v) {switch (v.getId()) {case R.id.start_service:Intent startIntent = new Intent(this, MyService.class);startService(startIntent); // 启动服务break;case R.id.stop_service:Intent stopIntent = new Intent(this, MyService.class);stopService(stopIntent); // 停止服务break;case R.id.bind_service:Intent bindIntent = new Intent(this, MyService.class);bindService(bindIntent, connection, BIND_AUTO_CREATE); // 绑定服务break;case R.id.unbind_service:unbindService(connection); // 解绑服务break;case R.id.start_intent_service:// 打印主线程的idLog.d("MainActivity", "Thread id is " + Thread.currentThread(). getId());Intent intentService = new Intent(this, MyIntentService.class);startService(intentService);break;default:break;}}}
package com.example.servicetest;import android.app.IntentService;
import android.content.Intent;
import android.util.Log;public class MyIntentService extends IntentService {public MyIntentService() {super("MyIntentService"); // 调用父类的有参构造函数}@Overrideprotected void onHandleIntent(Intent intent) {// 打印当前线程的idLog.d("MyIntentService", "Thread id is " + Thread.currentThread(). getId());}@Overridepublic void onDestroy() {super.onDestroy();Log.d("MyIntentService", "onDestroy executed");}}
package com.example.servicetest;import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Binder;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
import android.util.Log;public class MyService extends Service {public MyService() {}private DownloadBinder mBinder = new DownloadBinder();class DownloadBinder extends Binder {public void startDownload() {Log.d("MyService", "startDownload executed");}public int getProgress() {Log.d("MyService", "getProgress executed");return 0;}}@Overridepublic IBinder onBind(Intent intent) {return mBinder;}@Overridepublic void onCreate() {super.onCreate();Log.d("MyService", "onCreate executed");Intent intent = new Intent(this, MainActivity.class);PendingIntent pi = PendingIntent.getActivity(this, 0, intent, 0);Notification notification = new NotificationCompat.Builder(this).setContentTitle("This is content title").setContentText("This is content text").setWhen(System.currentTimeMillis()).setSmallIcon(R.mipmap.ic_launcher).setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher)).setContentIntent(pi).build();startForeground(1, notification);}@Overridepublic int onStartCommand(Intent intent, int flags, int startId) {Log.d("MyService", "onStartCommand executed");
// 服务要干的活,对于耗时的任务,需要开一个线程来处理new Thread(new Runnable() {@Overridepublic void run() {int count = 0;final String TAG = "MyService";for (int i = 0; i<3000000;i++){count++;if((count % 100) == 0){Log.d(TAG,"run:count=" + count);}}}}).start();return super.onStartCommand(intent, flags, startId);}@Overridepublic void onDestroy() {super.onDestroy();Log.d("MyService", "onDestroy executed");}}
service积极活动的生命时间(active lifetime)是从onStartCommand()或onBind()被调用开始,它们各自处理由startService()或bindService()方法传过来的Intent对象。
如果service是被开启的,那么它的活动生命周期和整个生命周期一同结束。
如果service是被绑定的,它们的活动生命周期是在onUnbind()方法返回后结束。
资料获取
https://mp.weixin.qq.com/s?__biz=Mzg4NTc0ODQwNA==&tempkey=MTE2OF9pdDEvcXNIV1QvMXZnZHA3TDBGWTVBUWYzVUgzd3NDQ0R0cGl5ZzY4MEdSVUNOMmxHWHI3WTJPcVcxWGNYVFVDa1hucjJLVUE4XzlWQmxCRVRkcHBvYmpzUVpZSEF1RVI3dnRkbjUyUWEyem1yTEF2OTczaTc5clRiSFFNcXVmcTBEU3JCOUhhYzF0LWYtU1Y0RXNaQTVfSXB3ek5tam8tREZ5bU9nfn4%3D&chksm=cfa566a0f8d2efb69a01b7843dcf26ec854cac4ac30b171f7e95d3911acb110c9904a1cd24ec&token=969508763&lang=zh_CN#rd
资料获取,公众号汪程序员,回复:2641603
Android四大组件之一服务相关推荐
- Android四大组件之一服务(Service)
Service(服务): 1. Android的四大组件之一,存在自己的生命周期 2. 一种可以在后台执行长时间运行操作而没有用户界面的应用组件,需要在AndroidManifest.xml配置相关信 ...
- Android 四大组件 —— 服务
一.服务是什么 服务(Service)是Android 中实现程序后台运行的解决方案,它非常适合用于去执行那些不需要和用户交互而且还要求长期运行的任务.服务的运行不依赖于任何用户界面,即使当程序被切换 ...
- Android四大组件之BroadCastReceiver
1. 基本概念 在Android 中,Broadcast 是一种广泛运用的在应用程序之间传输信息的机制.而BroadcastReceiver 是对发送出来的Broadcast 进行过滤接受并响应的一类 ...
- Android 四大组件之——Service(一)
一.什么是服务 服务,是Android四大组件之一, 属于 计算型组件. 长期后台运行的没有界面的组件 ,特点是无用户界面.在后台运行.生命周期长 二,什么时候使用服务? 天气预报:后台的连接服务 ...
- Android 四大组件之——Acitivity(一)
一,什么是Activity activity是Android组件中最基本也是最为常见用的四大组件之一.Android四大组件有Activity,Service服务,Content Provider内容 ...
- Android——四大组件、六大布局、五大存储
一.android四大组件 (一)android四大组件详解 Android四大组件分别为activity.service.content provider.broadcast receiver. 1 ...
- android四大组件的作用简书,Android四大组件是什么
Android四大组件是:活动.服务.广播接收器.内容提供商.它们的英文名称是ACTIVITY.SERVICE.BroadcastReceiver.Content Provider.四个组件分别起到不 ...
- Android 四大组件 与 MVC 架构模式
作为一个刚从JAVA转过来的Android程序员总会思考android MVC是什么样的? 首先,我们必须得说Android追寻着MVC架构,那就得先说一下MVC是个啥东西! 总体而来说MVC不能说是 ...
- Android四大组件---BroadcastReceiver
前言: BroadcastReceiver(广播接收器),属于 Android 四大组件之一 在 Android 开发中,BroadcastReceiver 的应用场景非常多 今天,我将详细讲解关于B ...
最新文章
- 2017《面向对象程序设计》寒假作业一
- 一对多分页查询mysql编写_一对多分页的SQL到底应该怎么写?
- Redis常见配置redis.conf
- Auto Encoder再学习
- Git使用中报错fatal: The current branch master has no upstream branch.解决方案
- 网络虚拟化叠加的八个用例
- linux ftp 150 无响应,FTP遇到150无响应
- C#自动切换Windows窗口程序,如何才能调出主窗口?
- 染色问题 —— 扇形涂色
- matlab怎样定义全局变量,Matlab如何定义公共变量
- 如何在WPS里添加字体?
- setoolkit制作简单钓鱼网站
- Watching the English:英国社会阶层攀爬指南?
- GPU 编程与CG 语言之阳春白雪下里巴人——CG学习读书笔记之数学函数(三)
- qpython oh下载_QPython OH
- 个性化Ubuntu壁纸如何添加
- Excel用正则表达式提取出输入正确的身份证号
- 【2 - 数据库是如何存储数据的】Sql Server - 郝斌(字段、记录、表;图形化界面及sql语句建表;六种约束;一对一、一对多、多对多、数据库关系图;主外键)
- 我是Papi酱,一个集才华与美貌于一身的过气网红
- 12C DELETE FROM wri$_adv_sqlt_rtn_planWHERE task_id = :tid AND exec_name = :execution_name