从Service的启动方式上,可以将Service分为Started Service和Bound Service。在使用Service时,要想系统能够找到此自定义Service,无论哪种类型,都需要在AndroidManifest.xml中声明:

<service android:name=".MyService">

一:StartService方式启动服务

Started Service相对比较简单,通过context.startService(Intent serviceIntent)启动Service,context.stopService(Intent serviceIntent)停止此Service。

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.servicetest"> <application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity> <service android:name=".MyService"> </service>
</application> </manifest>

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.servicetest.MainActivity"> <Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="启动服务"
android:id="@+id/btn_StartService" /> <Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="停止服务"
android:id="@+id/btn_StopService" />
</LinearLayout>
MainActivity:
package com.example.servicetest;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button; public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private Button startService;
private Button stopService; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startService=(Button)findViewById(R.id.btn_StartService);
stopService=(Button) findViewById(R.id.btn_StopService); startService.setOnClickListener(this);
stopService.setOnClickListener(this);
} @Override
public void onClick(View view) {
switch (view.getId()){
case R.id.btn_StartService:
//启动服务
Intent intentStart=new Intent(MainActivity.this,MyService.class);
startService(intentStart);
break;
case R.id.btn_StopService:
//停止服务
Intent intentStop=new Intent(MainActivity.this,MyService.class);
stopService(intentStop);
break;
}
}
}
MyService:
package com.example.servicetest;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log; import java.text.SimpleDateFormat;
import java.util.Date; /**
* Created by xch on 2016/9/5.
*/
public class MyService extends Service{ private boolean flag=true; @Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
} @Override
public void onCreate() {
super.onCreate();
Log.i("tag","服务被创建!"); } @Override
public void onDestroy() {
super.onDestroy();
Log.i("tag","服务被销毁!");
new MyThread().setFlagFalse();
} @Override
public int onStartCommand(Intent intent, int flags, int startId) { new MyThread().start(); return super.onStartCommand(intent, flags, startId);
} class MyThread extends Thread{
public void setFlagFalse(){
flag=false;
}
@Override
public void run() {
super.run(); while (flag){
//每隔一秒钟打印当前时间一次
//设置时间打印格式
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//24小时制
Date date=new Date();
String time=sdf.format(date);
Log.i("date",time);
try {
//沉睡1秒
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}

二. BoundService方式启动服务

bindService启动流程: context.bindService()  ——> onCreate()  ——> onBind()  ——> Service running  ——> onUnbind()  ——> onDestroy()  ——> Service stop

MainActivity:
package com.example.servicetest2;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button; public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private Button bindService,unBindService;
private Intent intent;
private MyServiceConn conn=new MyServiceConn(); @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); bindService=(Button)findViewById(R.id.btn_BindService);
unBindService=(Button)findViewById(R.id.btn_UnBindService); bindService.setOnClickListener(this);
unBindService.setOnClickListener(this);
} @Override
public void onClick(View v) {
switch (v.getId()){
case R.id.btn_BindService:
intent=new Intent(MainActivity.this,MyService.class);
bindService(intent,conn, Context.BIND_AUTO_CREATE);
break;
case R.id.btn_UnBindService:
intent=new Intent(MainActivity.this,MyService.class);
unbindService(conn);
break;
}
}
private class MyServiceConn implements ServiceConnection {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
//在服务绑定成功的时候执行
} @Override
public void onServiceDisconnected(ComponentName name) {
//当服务所在的进程被杀死,或崩溃的时候执行
}
}
}
MyService:
package com.example.servicetest2;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log; import java.text.SimpleDateFormat;
import java.util.Date; /**
* Created by xch on 2016/9/7.
*/
public class MyService extends Service {
private boolean flag=true;
private MyThread thread=new MyThread(); @Nullable
@Override
public IBinder onBind(Intent intent) {
thread.start();
return null;
} @Override
public void onCreate() {
Log.i("service","服务被创建!");
super.onCreate();
} @Override
public void onDestroy() {
super.onDestroy();
Log.i("service","服务被销毁!");
thread.setFlagFalse();
} @Override
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
} class MyThread extends Thread{
public void setFlagFalse(){
flag=false;
} @Override
public void run() {
super.run();
while (flag){
Date date=new Date();
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-mm-dd HH:mm:ss");
Log.i("date",sdf.format(date));
try {
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
} }
}
}

三.Service与Activity之间通讯

BoundService可以实现,但是startService没有这个特点。这里需要注意的是,利用bindService启动的Service无法获取这个Service对象,所以这里需要在Service中将对象返回,既然有返回就需要接收。so,看代码:

MyService:
package com.example.servicetest2;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log; import java.text.SimpleDateFormat;
import java.util.Date; /**
* Created by xch on 2016/9/7.
*/
public class MyService extends Service {
private boolean flag=true;
private MyThread thread;
private String format="yyyy-mm-dd HH:mm:ss"; //更改系统时间的输出格式
public void setFormat(String format){
this.format=format;
} public void changeFormat(String format){
if(thread!=null){
//调用方法,更改时间输出格式
setFormat(format);
}
} @Nullable
@Override
public IBinder onBind(Intent intent) {
thread.start();
//将代理类返回回去
return new ServiceBinder();
} @Override
public void onCreate() {
Log.i("service","服务被创建!");
thread=new MyThread();
super.onCreate();
} @Override
public void onDestroy() {
super.onDestroy();
Log.i("service","服务被销毁!");
thread.setFlagFalse();
} @Override
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
} class MyThread extends Thread{
public void setFlagFalse(){
flag=false;
} @Override
public void run() {
super.run();
while (flag){
Date date=new Date();
SimpleDateFormat sdf=new SimpleDateFormat(format);
Log.i("date",sdf.format(date));
try {
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
} }
} /**
* 当前服务的代理类,即可使用changeFormat()方法
* 需要通过IBinder将这个代理类返回回去,即onBinder()方法
*/
public class ServiceBinder extends Binder{
public void changeServiceBinder(String format){
if(thread!=null){
changeFormat(format);
}
} }
}

这里需要在service中定义一个代理类,并利用onBinder()方法返回去。

MainActivity:

package com.example.servicetest2;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button; public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private Button bindService,unBindService,changeFormat;
private Intent intent;
private MyServiceConn conn=new MyServiceConn();
//接收到的service对象
private MyService.ServiceBinder serviceBinder; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); bindService=(Button)findViewById(R.id.btn_BindService);
unBindService=(Button)findViewById(R.id.btn_UnBindService);
changeFormat=(Button)findViewById(R.id.btn_changeFormat); bindService.setOnClickListener(this);
unBindService.setOnClickListener(this);
changeFormat.setOnClickListener(this);
} @Override
public void onClick(View v) {
switch (v.getId()){
case R.id.btn_BindService:
intent=new Intent(MainActivity.this,MyService.class);
bindService(intent,conn, Context.BIND_AUTO_CREATE);
break;
case R.id.btn_UnBindService:
intent=new Intent(MainActivity.this,MyService.class);
unbindService(conn);
break;
case R.id.btn_changeFormat:
serviceBinder.changeServiceBinder("HH:mm:ss");
break;
}
}
private class MyServiceConn implements ServiceConnection {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
//在服务绑定成功的时候执行,同时接收到了IBinder对象(类型为代理类对象,因为onBinder方法返回了代理类对象)
serviceBinder= (MyService.ServiceBinder) service;
} @Override
public void onServiceDisconnected(ComponentName name) {
//当服务所在的进程被杀死,或崩溃的时候执行
}
}
}

这里实现了ServiceConnection接口的自定义类需要实现如上两个方法,其中onServiceConnected(ComponentName name, IBinder service)方法能获取onBinder()返回的service对象。

 结果:


Android学习总结——Service组件的更多相关文章

  1. Android中的Service组件具体解释

    Service与Activity的差别在于:Service一直在后台执行,他没实用户界面,绝不会到前台来. 一,创建和配置Service 开发Service须要两个步骤:1.继承Service子类,2 ...

  2. 我有一壶酒 Android学习之Service(1)--->BinderService方式

    本文只讨论扩展Binder类 创建一个Binder.xml <?xml version="1.0" encoding="utf-8"?> <L ...

  3. Android学习之Service(1)--->Started方式

    界面退出后进程程序还在运行,不会被杀死,如音乐播发器.后台下载等 注:本文只讨论Started方式 main.xml代码分析 <?xml version="1.0" enco ...

  4. 【Android学习】Service&Boradcast初步

    Service初步 掌握Service概念 掌握Service分类 Service开发能力具备 了解Service和intentService类的区别 重点难点 StartService和BoundS ...

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

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

  6. Android 学习笔记 Service

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

  7. android学习笔记 Service

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

  8. Android学习笔记⑧——UI组件的学习AdapterView相关2

    前面都是用ListView控件来配合Adapter做的一些实例,这次我们来见识一下GridView与Adapter之间的爱恨情仇.... GridView是用于在界面上按行.列分布的方式来显示多个的组 ...

  9. Android学习笔记⑦——UI组件的学习AdapterView相关1

    AdapterView是一个非常重要的组件之一,他非常灵活,所以得好好学...AdapterView本身是一个抽象类,派生出来的子类用法也十分相似,只是界面有一定的区别,因此本节把他们归为一类 Ada ...

随机推荐

  1. hdu 1885 Key Task(bfs+状态压缩)

    Problem Description The Czech Technical University years of its existence . Some of the university b ...

  2. VS快捷编码方式

    概念: 代码段是将预先定义好的可重用代码块快速插入到代码文件中,代码段提高了开发效率,增强了代码的可重用性:既节约了时间,又实现了不同开发人员间代码的共享.同时也可保证同一项目中代码风格的统一.   ...

  3. Python网络爬虫(6)--爬取淘宝模特图片

    经过前面的一些基础学习,我们大致知道了如何爬取并解析一个网页中的信息,这里我们来做一个更有意思的事情,爬取MM图片并保存.网址为https://mm.taobao.com/json/request_t ...

  4. js的 new image()---转

    创建一个Image对象:var a=new Image(); 定义Image对象的src: a.src=”xxx.gif”;    这样做就相当于给浏览器缓存了一张图片. 图像对象: 建立图像对象:图 ...

  5. C#线程池ThreadPool的理解

    在多线程编程中,线程的创建和销毁是非常消耗系统资源的,因此,C#引入了池的概念,类似的还有数据库连接池,这样,维护一个池,池内维护的一些线程,需要的时候从池中取出来,不需要的时候放回去,这样就避免了重 ...

  6. A Typical Homework(学生信息管理系统)

    A Typical Homework(a.k.a Shi Xiong Bang Bang Mang) Hi, I am an undergraduate student in institute of ...

  7. (原)ubuntu16在torch中使用caffe训练好的模型

    转载请注明出处: http://www.cnblogs.com/darkknightzh/p/5783006.html 之前使用的是torch,由于其他人在caffe上面预训练了inception模型 ...

  8. JS控制文本框中的密码显示/隐藏功能

    <html> <head> <title>[荐]JS控制文本框中的密码显示/隐藏功能_网页代码站(www.6a8a.com)</title> <s ...

  9. javascript get获取参数

    function GetQueryString(name) { var reg = new RegExp("(^|&)"+ name +"=([^&]*) ...

  10. POJ 2488 A Knight's Journey(DFS)

    A Knight's Journey Time Limit: 1000MSMemory Limit: 65536K Total Submissions: 34633Accepted: 11815 De ...