前段时间做项目,用到service了,当时只是匆匆忙忙的用了,具体什么原理也不知道,项目上线了,终于有时间学习了,小菜鸟终于可以整理一下

根据程序来看一下service的生命周期(由于布局只有几个按钮,这里就不贴图了)

1.MainActivity.java

package com.sdufe.thea.guo;import android.os.Bundle;
import android.os.IBinder;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;public class MainActivity extends Activity implements OnClickListener {private Button button1, button2, button3, button4, button5, button6;private String TAG = "MainActivity";private ServiceConnection conn;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);initView();conn = new ServiceConnection() {@Overridepublic void onServiceDisconnected(ComponentName name) {Log.d(TAG, "onServiceDisconnected");}@Overridepublic void onServiceConnected(ComponentName name, IBinder service) {Log.d(TAG, "onServiceConnected");}};}private void initView() {button1 = (Button) findViewById(R.id.button1);button2 = (Button) findViewById(R.id.button2);button3 = (Button) findViewById(R.id.button3);button4 = (Button) findViewById(R.id.button4);button5 = (Button) findViewById(R.id.button5);button6 = (Button) findViewById(R.id.button6);button1.setOnClickListener(this);button2.setOnClickListener(this);button3.setOnClickListener(this);button4.setOnClickListener(this);button5.setOnClickListener(this);button6.setOnClickListener(this);}@Overridepublic void onClick(View v) {Intent intent = new Intent(MyService.ACTION);switch (v.getId()) {// 启动服务case R.id.button1:startService(intent);break;// 绑定服务case R.id.button2:bindService(intent, conn, BIND_AUTO_CREATE);break;// 解除服务case R.id.button3:unbindService(conn);break;// 结束服务case R.id.button4:stopService(intent);break;// myservicecase R.id.button5:startService(new Intent(this, MyService.class));break;// myintentservicecase R.id.button6:startService(new Intent(this, MyIntentService.class));break;}}}

布局中存在六个button,其中前四个分别是测试service的生命周期的,最后两个测试service的,由于service不在单独的进程中,又不是线程,还有就是我们习惯性把耗时的操作放在service中,所以来测试一下service和intentService

2.MyService.java

package com.sdufe.thea.guo;import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;public class MyService extends Service {private String TAG="MyService";public static final String ACTION="com.sdufe.thea.guo.MyService";@Overridepublic IBinder onBind(Intent intent) {Log.d(TAG, TAG+"onBind");return null;}@Overridepublic void onCreate() {Log.d(TAG, TAG+"onCreate");super.onCreate();}@Override@Deprecatedpublic void onStart(Intent intent, int startId) {Log.d(TAG, TAG+"onStart");try {Thread.sleep(3000);} catch (InterruptedException e) {e.printStackTrace();}Log.d(TAG, TAG+"睡眠结束");super.onStart(intent, startId);}@Overridepublic int onStartCommand(Intent intent, int flags, int startId) {Log.d(TAG, TAG+"onStartCommand");return super.onStartCommand(intent, flags, startId);}@Overridepublic boolean onUnbind(Intent intent) {Log.d(TAG, TAG+"onUnbind");return super.onUnbind(intent);}@Overridepublic void onDestroy() {Log.d(TAG, TAG+"onDestroy");super.onDestroy();}}

在MyService中,主要写了service,为了测试service和IntentService,在OnStart中加入了一段代码,无关大雅,暂时先忽略

3.在AndroidManifest.xml给service注册一下

<service android:name="com.sdufe.thea.guo.MyService" ><intent-filter><action android:name="com.sdufe.thea.guo.MyService" /></intent-filter></service>

首先点击启动服务:

点击结束服务:


点击绑定服务:

结束服务:

注:服务都是成对出现

下面来说一下Service和IntentService,一般费时的操作会放在service,但是当时间长时,会出现Application Not Responding

下面呈上service和IntentService源码,一看就懂了

public abstract class Service extends ContextWrapper implements ComponentCallbacks2 {private static final String TAG = "Service";public Service() {super(null);}
}
public abstract class IntentService extends Service {private volatile Looper mServiceLooper;private volatile ServiceHandler mServiceHandler;private String mName;private boolean mRedelivery;private final class ServiceHandler extends Handler {public ServiceHandler(Looper looper) {super(looper);}@Overridepublic void handleMessage(Message msg) {onHandleIntent((Intent)msg.obj);stopSelf(msg.arg1);}}
}

瞄一眼源码应该就懂了,耗时比较长的还是用IntentService比较靠谱

很多时候服务和通知会一起用,这里也顺便写了写通知,代码如下:

package com.sdufe.thea.guo;import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.util.Log;public class MyIntentService extends IntentService {private String TAG = "MyIntentService";private NotificationManager notificationManager;public MyIntentService() {super("***");}@Overrideprotected void onHandleIntent(Intent intent) {Log.d(TAG, TAG + "onStart");try {Thread.sleep(30000);} catch (InterruptedException e) {e.printStackTrace();}notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);@SuppressWarnings("deprecation")Notification notification = new Notification(R.drawable.ic_launcher,"通知", System.currentTimeMillis());intent = new Intent(getApplicationContext(), SecondActivity.class);PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent, 0);notification.setLatestEventInfo(getApplicationContext(), "标题", "内容...",pendingIntent);notificationManager.notify(0, notification);Log.d(TAG, TAG + "睡眠结束");}
}

ok,差不多先分享这些

源码地址:http://download.csdn.net/detail/elinavampire/8115975

简单demo诉说Service And Intentservice相关推荐

  1. Ocelot 入门Demo系列(01-Ocelot极简单Demo及负载均衡的配置)

    来源:https://www.cnblogs.com/7tiny/p/10493805.html [前言] Ocelot是一个用.NET Core实现并且开源的API网关,它功能强大,包括了:路由.请 ...

  2. 服务网关Ocelot 入门Demo系列(01-Ocelot极简单Demo及负载均衡的配置)

    服务网关Ocelot 入门Demo系列(01-Ocelot极简单Demo及负载均衡的配置) 原文:服务网关Ocelot 入门Demo系列(01-Ocelot极简单Demo及负载均衡的配置) [前言] ...

  3. JavaWeb开发:从购买服务器到简单demo运行

    写这篇文章的目的: 一个是为了记录实施过程,方便自己日后查阅: 另一个是给项目组成员提供一个参考,方便他们以后搭建自己的项目环境: 当然若能帮助到更多的朋友,那就再好不过了:D 需要注意: 我本身也是 ...

  4. Spring Boot自动装配过程解析及简单Demo演示

    文章目录 1.约定大于配置 2.自动装配原理 2.1.`@SpringBootApplication` 2.2.`@EnableAutoConfiguration` 2.3.`@Import` 2.4 ...

  5. 使用腾讯云实现录音语音转换文字简单DEMO

    使用腾讯云实现录音语音转换文字简单DEMO 感谢 对接腾讯云 新建springboot项目 创建一个接口(VoiceService) 创建controller层(VoiceController) 加入 ...

  6. IDEA 开发一个简单的 web service 项目,并打包部署到 Tomcat

    文章目录 实现的效果 一.创建 web service 项目 二.测试类运行 web service 服务端 三.IDEA 打包 web service 项目 四.web service 项目部署到 ...

  7. EPSON机器人建立TCP/IP通讯的简单demo

    以下为我近期研究EPSON机器人通讯的经验总结,主要实现机械手接收相机发送过来的数据,从而达到对应的位置,及其简单demo. 欢迎加入知识星球[3D视觉工坊],进行交流学习.

  8. Solr配置与简单Demo[转]

    Solr配置与简单Demo 简介: solr是基于Lucene Java搜索库的企业级全文搜索引擎,目前是apache的一个项目.它的官方网址在http://lucene.apache.org/sol ...

  9. VC++ 拖放编程简单Demo

    微软的编程类库都带有拖放编程的接口:下面看一个最简单demo:win7, vc6:新建一个对话框工程: 添加一个列表框控件:设置 接受文件 属性: 在 类向导-Class Info 做如下选择: 为W ...

最新文章

  1. linux如何进入单用户模式
  2. 【Ansible】3个让Ansible性能飞起的简单优化方案!
  3. 八皇后java_经典八皇后问题:Java语言
  4. 【直播】如何设计性能更强大的深度卷积神经网络
  5. centos 服务器装与python34源码安装
  6. 100. 相同的树 golang
  7. Qt实现对json文件的解析
  8. pythonの鉴黄之路(二)——图片转base64码
  9. java虚引用_深入了解JAVA 虚引用
  10. mysql 删除了授权_mysql用户授权访问与删除授权
  11. 勿以善小而不为--PPP认证之CHAP与PAP的实现与区别
  12. n != n, n == -n
  13. Android sdk下载安装配置教程
  14. 九九乘法表c语言带表头,C语言-九九乘法表
  15. Oracle、MySQL、SQL server数据库去重
  16. MybatisPlus实现数据库加解密
  17. 第89章、系统服务之SMS服务(从零开始学Android)
  18. jeDate—选择日期后,再点开重新选择时间,日期会被置为今日日期
  19. python气象实时监控系统_Python绘图 | 国家气象局开源预报检验库(多图预警)
  20. vant步进器传值_有赞开源的Vue 2.0 的 Mobile 组件库 Vant

热门文章

  1. 面试 | Java 算法的 ACM 模式
  2. c语言中个各标点符号作用,在C语言中各个标点符号的作用是什么?
  3. 集货运输优化:数学建模步骤,Python实现蚁群算法(解决最短路径问题), 蚁群算法解决旅行商问题(最优路径问题),节约里程算法
  4. c语言多变量输入,技多不压身——C语言(五)变量,常量和输入输出
  5. 01 guava-cache:LRU算法
  6. 盘点最受欢迎的十大技术文章
  7. FOC项目知识点总结五 | FOC流程总述
  8. 小葫芦-游戏直播行业数据报告——附下载链接
  9. SQL语句基础MySQL版
  10. win7计算机将在一分钟重启,Win7系统出现提示: “Windows已遇到关键问题,将在一分钟后自动重新启动。”...