一、创建Service

  1.创建一个myService类,来继承Service。重写其中的方法,包括:onCreate(),onStartCommend(),onDestroy(),onBind()方法是自动重载的。

    1.1 onCreate():创建Service的时候调用,只调用一次。

    1.2 onStartCommend():执行Service的时候调用,执行几次,调用几次。

    1.3 onDestroy():在销毁Service的时候调用,只调用一次。

    1.4 onBind():在bindService的时候调用。只调用一次。

  1.2 myService代码如下:

package com.wangpei.service;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log; /**
* 作者:WangPei on 2015/7/9 09:48
* 邮箱:460977141@qq.com
*/
public class myService extends Service { private static final String TAG = "myInfo";
  //需要返回Binder实例
private MyBinder myBinder = new MyBinder(); @Override
public IBinder onBind(Intent intent) {
return myBinder;
} @Override
public void onCreate() {
Log.i(TAG,"onCreate is excute");
super.onCreate();
} @Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(TAG,"onStartCommand is excute");
return super.onStartCommand(intent, flags, startId);
} @Override
public void onDestroy() {
Log.i(TAG,"onDestroy is excute");
super.onDestroy();
} class MyBinder extends Binder{ public void startDownload(){
        //模拟下载任务
Log.i(TAG,"startDownload is excute");
}
}
}

二、startService AND stopService

  2.1 startService

    2.1.1 代码如下:

Intent startIntent = new Intent(MainActivity.this,myService.class);
startService(startIntent);

    2.1.2 调用myService类中的方法顺序如下:

        onCreate() ---> onStartCommend() ---先创建Service,然后在执行。

  2.2 stopService 代码如下:

    2.2.1 代码如下:

Intent stopIntent = new Intent(MainActivity.this,myService.class);
stopService(stopIntent);

    2.2.2 调用myService类中的方法顺序如下:

        onDestroy() --直接被销毁。

三、bindService AND unBindService

  3.1 创建ServiceConnection:

//初始化myService中的binder
private myService.MyBinder myBinder; private ServiceConnection connection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
myBinder = (myService.MyBinder) service;
       //启动下载任务
myBinder.startDownload();
} @Override
public void onServiceDisconnected(ComponentName name) { }
};

    3.1.1 onServiceConnected()方法,是在Activity和Service建立连接的时候,进行调用。

    3.1.1 onServiceDisconnected()方法,onServiceDisconnected()方法不是解除关联的时候调用,而是发生异常时调用的。

  3.2 bindService 代码如下:

Intent bindIntent = new Intent(MainActivity.this,myService.class);
bindService(bindIntent,connection,BIND_AUTO_CREATE);

    3.2.1 BIND_AUTO_CREATE:意思是在绑定Service的时候,进行自动创建。

  3.3 unBindService 代码如下:

unbindService(connection);

  3.4 注意 如果同时startService和bindService,必须要stopService和unBindService,才能onDestroy()该Service。

   3.5 额外的东西

    楼主文中是有说明Service和Activity是如何通信的;首先在自定义的Service类中覆盖onBind(Intent intent)方法,返回一个Binder子类的对象,在自定义的Binder子类中可以定义一些方法;然后再Activity创建个ServiceConnection对象,并实现其onServiceConnected(ComponentName name, IBinder service) 方法,在这个方法中将传入的IBinder对象强转为在Service中定义的Binder子类,这样就拿到了Service中的某个对象的引用了,想怎通信都行;但要使onServiceConnected方法被回调,还需要调用bindService方法,把ServiceConnection的对象当作参数传过去......

四、Service AND Thread 的关系

  4.1 Service

    4.1.1 Service旨在后台运行,并且Service也是在主线程中运行的。

    4.1.2 Service就不同了,所有的Activity都可以与Service进行关联,然后可以很方便地操作其中的方法,即使Activity被销毁了,之后只要重新与Service建立关联,就又能够获取到原有的Service中Binder的实例。

    4.1.3 使用Service来处理后台任务,Activity就可以放心地finish,完全不需要担心无法对后台任务进行控制的情况。

    4.1.4 我们可以在Service中再创建一个子线程,然后在这里去处理耗时逻辑就没问题了。

    4.1.5 较为标准的Service写法:

private MyBinder myBinder;

@Override  
public Binder onBind(Intent intent){
  return myBinder;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
new Thread(new Runnable() {
@Override
public void run() {
// 开始执行后台任务
}
}).start();
return super.onStartCommand(intent, flags, startId);
} class MyBinder extends Binder { public void startDownload() {
new Thread(new Runnable() {
@Override
public void run() {
// 执行具体的下载任务
}
}).start();
} }

  4.2 Thread

    4.2.1 Thread是在子线程中运行的,旨在不影响主线程的运行。

4.2.2 Activity很难对Thread进行控制,当Activity被销毁之后,就没有任何其它的办法可以再重新获取到之前创建的子线程的实例;

五、前台Service

  5.1 需要在通知栏显示,点击之后,可以跳转到Activity。优点,可以保持持续的运行。比如说墨迹天气,它的Service在后台更新天气数据的同时,还会在系统状态栏一直显示当前天气的信息。具体实现如下:

public class MyService extends Service {  

    public static final String TAG = "MyService";  

    private MyBinder mBinder = new MyBinder();  

    @Override
public void onCreate() {
super.onCreate();
    //先定义通知
Notification notification = new Notification(R.drawable.ic_launcher,
"有通知到来", System.currentTimeMillis());
    //跳转意图
Intent notificationIntent = new Intent(this, MainActivity.class);
    //将意图转换为等待意图
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
notificationIntent, 0);
    //初始化通知
notification.setLatestEventInfo(this, "这是通知的标题", "这是通知的内容",
pendingIntent);
    //然后调用startForeground()方法就可以让MyService变成一个前台Service,并会将通知的图片显示出来。
startForeground(1, notification);
Log.d(TAG, "onCreate() executed");
} ......... }

 六、远程Service

  6.1 远程Service介绍:

        在注册service的时候,添加属性:remote即可激活远程service。远程service,是不同有主进程的service。直接可以在内部执行耗时操作,并且不影响主进程的使用。但是,有一个弊端。远程service没有办法和Activity进行绑定。因为,远程service是不同于应用程序主进程的进程,他们之间无法建立连接的。

     那么如何,才能使Activity和远程service建立连接呢?这里我们需要使用AIDL。接口定义语言来实现跨进程通信技术。

  6.2 AIDL(android interface definition language)的使用:

    6.2.1 使用方法,先建立一个后缀为AIDL的文件,这是一个接口文件。然后进行编译。系统会自动生成一个java文件。然后我们就可以进行使用了。

// IMyAidlInterface.aidl
package com.wangpei.service; // Declare any non-default types here with import statements interface IMyAidlInterface {
/**
* Demonstrates some basic types that you can use as parameters
* and return values in AIDL.
*/
int plus(int a, int b);
String toUpperCase(String str);
}

   6.2.2 然后进行编译,系统会自动生成一个相应的java文件。此时,我们就可以使用它了。

在MyService中进行使用(对aidl中的方法,进行重写。):

package com.wangpei.service;

import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log; /**
* 作者:WangPei on 2015/7/9 09:48
* 邮箱:460977141@qq.com
*/
public class myService extends Service { private static final String TAG = "myInfo";
private MyBinder myBinder = new MyBinder(); @Override
public IBinder onBind(Intent intent) {
return mBinder;
} IMyAidlInterface.Stub mBinder = new IMyAidlInterface.Stub() {
@Override
public int plus(int a, int b) throws RemoteException {
return a+b;
} @Override
public String toUpperCase(String str) throws RemoteException {
if(str != null){ return str.toUpperCase();
}else {
return null;
}
}
}; @Override
public void onCreate() {
Log.i(TAG,"onCreate is excute");
// Log.i(TAG,"myService thread is :"+Thread.currentThread().getName()); /**
* 前台Service的使用
*/
// Notification notification = new Notification(R.drawable.ic_launcher,"这是通知的内容",System.currentTimeMillis());
// Intent notificationIntent = new Intent(this,MainActivity.class);
// PendingIntent pendingIntent = PendingIntent.getActivity(this,0,notificationIntent,0);
// notification.setLatestEventInfo(this,"这是通知的标题","这是主要内容",pendingIntent);
// startForeground(1,notification); super.onCreate();
} @Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(TAG,"onStartCommand is excute");
return super.onStartCommand(intent, flags, startId);
} @Override
public void onDestroy() {
Log.i(TAG,"onDestroy is excute");
super.onDestroy();
} class MyBinder extends Binder{ public void startDownload(){
Log.i(TAG,"startDownload is excute");
}
}
}

  6.2.3 最后在Activity中进行调用,即可,使用Aidl中,所定义的方法。

 private ServiceConnection connection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
// myBinder = (myService.MyBinder) service;
// myBinder.startDownload();
iMyAidlInterface = IMyAidlInterface.Stub.asInterface(service);
try {
int result = iMyAidlInterface.plus(9,15);
String str = iMyAidlInterface.toUpperCase("wang pei"); Log.i(TAG,result+"");
Log.i(TAG,str);
} catch (RemoteException e) {
e.printStackTrace();
}
}

  

    

  

【笔记】Service的使用的更多相关文章

  1. Android 学习笔记 Service服务与远程通信...(AIDL)

    PS:这一章节看的我有几分迷茫,不是很容易理解...不过还好总算是明白了一大半了...基本的迷惑是解决了... 学习内容: 1.跨应用启动服务... 2.跨应用绑定服务... 3.跨应用实现通信... ...

  2. Android 学习笔记 Service

    PS:前几篇的内容光是上代码了,也没有细细的讲解..感觉这样写很不好..因此还是多一些讲解吧... 学习内容: 1.了解Service... 2.Service的启动与停止.. 3.绑定与取消绑定Se ...

  3. android学习笔记 Service

    Service(服务): 长期后台运行的没有界面的组件 android应用什么地方需要用到服务? 天气预报:后台的连接服务器的逻辑,每隔一段时间获取最新的天气信息.股票显示:后台的连接服务器的逻辑,每 ...

  4. Angular 学习笔记——service &constant

    <!DOCTYPE HTML> <html ng-app="myApp"> <head> <meta http-equiv="C ...

  5. 安卓组件service

    [转]http://blog.csdn.net/ithomer/article/details/7364024 一. Service简介 Service是android 系统中的四大组件之一(Acti ...

  6. Android Service 服务(三)—— bindService与remoteService

    (转自:http://blog.csdn.net/ithomer/article/details/7366396)   一.bindService简介 bindService是绑定Service服务, ...

  7. 时隔两年最近再次折腾opensuse 的一些笔记 - opensuse linux java service shell

    时隔两年最近再次折腾opensuse 的一些笔记 - opensuse linux java service shell opensuse 一些常用命令:    service xxx start/s ...

  8. Dynamic CRM 2013学习笔记(二十五)JS调用web service 实现多条记录复制(克隆)功能

    前面介绍过如何克隆一条当前的记录: Dynamic CRM 2013学习笔记(十四)复制/克隆记录 , 主要是通过界面上加一个字段,单击form上的clone 按钮时,改变这个字段的值以触发插件来实现 ...

  9. Dynamic CRM 2013学习笔记(二十九)报表设计:reporting service 报表开发常见问题

    在报表开发过程中,经常会遇到各种各样的问题,比如The report cannot be displayed. (rsProcessingAborted),一点有意义的提示都没有:再就是分页问题,经常 ...

  10. 安卓第十三天笔记-服务(Service)

    安卓第十三天笔记-服务(Service) Servcie服务 1.服务概念 服务 windows 服务没有界面,一直运行在后台, 运行在独立的一个进程里面 android 服务没有界面,一直运行在后台 ...

随机推荐

  1. vue 2.0

    vue2.0 据说也出了很久了,博主终于操了一次实刀. 整体项目采用  vue +  vue-router +  vuex (传说中的vue 全家桶 ),构建工具使用尤大大推出的vue-cli 项目是 ...

  2. DOM hash

    前段时间做的一个H5专题,用到了hash解决问题,特意记录一下.DOM hash的详细内容可以点击链接查看. hash就是uri中#及后面的部分,例如:www.google.com.hk#123的#1 ...

  3. JAV07接口与继承之动手动脑问题解决

    动手动脑:请自行编写代码测试以下特性:在子类中,若要调用父类中被覆盖的方法,可以使用super关键字. 1.源代码: package Work; class A{ public A(){ System ...

  4. C# 反射浅析

    反射是一个运行库类型发现的过程.通过反射可以得到一个给定程序集所包含的所有类型的列表,这个列表包括给定类型中定义的方法.字段.属性和事件.此外,通过反射也可以动态的发现一组给定类支持的接口.方法的参数 ...

  5. php案列分享

    <?php function GetfourStr($len) { $chars_array = array( "0", "1", "2&quo ...

  6. Java—事件和多线程机制

    一  事件 1.1 事件源 图形用户界面上每个可能产生事件的组件称为事件源. 1.2 事件监听者 Java系统中注册的用于接收特殊事件的类.不同的事件对应着不同的监听者,要想事件被监听者监听并处理,则 ...

  7. tomcat-maven-plugin

    tomcat-maven-plugin , 我们可以使用这个插件把web应用一键式的部署到一个远程的tomcat中.   步骤1  : 修改 tomcat/conf/tomcat-users.xml ...

  8. Android之ViewPager组件实现左右滑动View

    什么是ViewPager VIewPager是安卓3.0之后提供的新特性,继承自ViewGroup,专门用来实现左右滑动切换View的效果.如果想向下兼容需要 android-support-v4.j ...

  9. FZU 2150 Fire Game

    Fire Game Time Limit:1000MS     Memory Limit:32768KB     64bit IO Format:%I64d & %I64u Submit St ...

  10. EF6 CodeFirst+Repository+Ninject+MVC4+EasyUI实践(九)

    前言 这一篇我们将完成系统的权限设置功能以及不同角色用户登录系统后动态加载菜单.注意:此示例权限只针对菜单级,如果园友需要更复杂的系统权限设置,可以拓展到按钮级或属性级. 用户的登录采用Form认证来 ...