1、通过startservice方法启动一个服务。service不能自己启动自己。若在一个服务中启动一个activity则,必须是申明一个全新的activity任务TASK。通过startservice方法启动的服务不会随着启动组件的消亡而消亡,而是一直执行着。

Service生命周期 onCreate()-------->onStartCommand()----------->onDestroy()

startService()启动一个服务后。若在该服务做耗时操作且没有写线程,则会导致主线程堵塞!

服务启动执行后会一直执行onStartCommand()方法。

2、用bindService启动一个服务,该服务和activity是绑定在一起的:启动时,先调用onCreate()------>onBind()--------->onServiceConnected(),启动服务的组件消亡,服务也就消亡了。

3、AIDL服务调用方式

demo下载地址:http://download.csdn.net/detail/u014600432/8175529

1)服务端代码:

首先定义一个接口描写叙述语言的接口:

package com.example.service;
interface DataService{
double getData(String arg); }

然后定义服务组件代码:

/**
*Version:
*author:YangQuanqing
*Data:
*/
package com.example.android_aidl_service; import com.example.service.DataService; import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.os.RemoteException; /**
* @author YangQuanqing yqq
*
*/
public class MyService extends Service { @Override
public IBinder onBind(Intent arg0) {
<span style="color:#ff0000;">//返回binder由didl文件生成</span>
return binder;
}
//定义给client调用的方法 (aidl文件)
Binder binder=new <span style="color:#ff0000;">DataService.Stub()</span> { @Override
public double getData(String arg) throws RemoteException {
if(arg=="a"){
return 1;
}
if(arg=="b"){
return 2;
} return 0;
}
}; }

服务端的清单文件:

<?xml version="1.0" encoding="utf-8"?

>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.android_aidl_service"
android:versionCode="1"
android:versionName="1.0" > <uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" /> <application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.android_aidl_service.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name="com.example.android_aidl_service.MyService"
>
<intent-filter>
<!-- 意图过滤器要把aidl包名加类名 -->
<action android:name="com.example.service.DataService"/>
</intent-filter>
</service>
</application> </manifest>

client编码:

把aidl文件包复制到client。client代码例如以下:

package com.example.android_aidl_client;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView; import com.example.service.DataService; public class MainActivity extends Activity {
private Button btn1,btn2;
//定义一个AIDL实例
private DataService dataService;
private TextView tv; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn1=(Button)this.findViewById(R.id.button1);
btn2=(Button)this.findViewById(R.id.button2);
tv=(TextView)this.findViewById(R.id.textView1);
//绑定服务
btn1.setOnClickListener(new OnClickListener() { @Override
public void onClick(View v) {
Intent intent=new Intent(DataService.class.getName());
//启动服务
bindService(intent, conn, BIND_AUTO_CREATE);
}
});
//调用服务的方法
btn2.setOnClickListener(new OnClickListener() { @Override
public void onClick(View v) {
try {
int result=(int) dataService.getData("a");
tv.setText(result+"");
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} }
});
}
//客户端与服务交互
private ServiceConnection conn=new ServiceConnection() { @Override
public void onServiceDisconnected(ComponentName name) { } @Override
public void onServiceConnected(ComponentName name, IBinder service) {
//传入service
dataService=DataService.Stub.asInterface(service);
}
};
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
} }

这样就能够完毕进程间通信了。

4、用bindService启动服务并訪问本地服务的方法。

訪问界面代码:

package com.example.android_service_binder;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView; import com.example.android_service_binder.MyService.LocalBinder; public class MainActivity extends Activity {
//销毁绑定
@Override
protected void onStop() {
super.onStop();
if(flag)
{
//解除绑定
unbindService(serviceConnection);
flag=false;
} } //绑定Service
@Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
/*Intent intent=new Intent(MainActivity.this,MyService.class);
//启动service
bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);*/
} private Button btnBinder=null;
private Button btnCall=null;
private TextView tv=null;
private MyService myService;//service实例
private boolean flag=false;//默认不绑定 @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnBinder=(Button)this.findViewById(R.id.button1);
btnCall=(Button)this.findViewById(R.id.button2);
tv=(TextView)this.findViewById(R.id.textView1);
btnBinder.setOnClickListener(new OnClickListener() { @Override
public void onClick(View v) {
Intent intent=new Intent(MainActivity.this,MyService.class);
//启动service
bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
}
});
//调用service方法
btnCall.setOnClickListener(new OnClickListener() { @Override
public void onClick(View v) {
//处于绑定状态
if(flag)
{
int result=myService.getRandom();
tv.setText("<<<<<"+result);
}
}
}); } private ServiceConnection serviceConnection= new ServiceConnection(){
//连接
@Override
public void onServiceConnected(ComponentName arg0, IBinder iBinder) {
//获得服务的The IBinder of the Service's communication channel, which you can now make calls on.
LocalBinder binder=(LocalBinder) iBinder;
//获得服务
myService=binder.getService(); flag=true; }
//不连接
@Override
public void onServiceDisconnected(ComponentName arg0) {
flag=false; } }; @Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
} }

服务组件代码:

/**
*Version:
*author:YangQuanqing
*Data:
*/
package com.example.android_service_binder; import java.util.Random; import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder; /**
* @author YangQuanqing yqq
*
*/
public class MyService extends Service { private final LocalBinder lb=new LocalBinder();
private final Random num=new Random(); @Override
public IBinder onBind(Intent arg0) {
// 返回本地Binder的子类实例
return lb;
}
//定义一个本地Binder类继承Binder
public class LocalBinder extends Binder{
//获得Servie子类当前实例给client
public MyService getService(){
return MyService.this;
} }
public int getRandom(){ return num.nextInt(98);
} }

通过该demo能够訪问本地服务里面的方法。

demo下载地址:http://download.csdn.net/detail/u014600432/8175633

5、IntentService

本质是开启一个线程来完毕耗时操作。

IntentService生命周期:

onCreate()------->onStartCommand()--------->onHandleIntent()--------->onDestroy()

/**
*Version:
*author:YangQuanqing
*Data:
*/
package com.example.android_intentservice; import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException; import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils; import android.app.IntentService;
import android.content.Intent;
import android.os.Environment;
import android.widget.Toast; /**
* @author YangQuanqing 不须要开启线程(看源代码知道是自己封装了开启线程),不须要关闭服务,自己关闭,单线程下载数据
*
* 一定要记得实例化! ! ! */
public class DownLoadService extends IntentService { @Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
} public DownLoadService() {
super("DownLoadService"); } // 仅仅需复写例如以下方法 // 在该方法中运行操作
@Override
protected void onHandleIntent(Intent intent) {
// 获得提取网络资源的实例
HttpClient httpClient = new DefaultHttpClient();
// 设置请求方式
HttpPost httpPost = new HttpPost(intent.getStringExtra("url"));
// 设置存储路径
File file = new File(Environment.getExternalStorageDirectory(),
"IntentService.gif");
// 定义输出流用于写
FileOutputStream fileOutputStream = null;
byte[] data = null;// 网络数据 try {
// 运行请求获得响应
HttpResponse httpResponse = httpClient.execute(httpPost);
// 推断响应状态码
if (httpResponse.getStatusLine().getStatusCode() == 200) {
// 获得响应实体
HttpEntity httpEntity = httpResponse.getEntity();
// 获得网络数据
data = EntityUtils.toByteArray(httpEntity);
// 推断SD卡是否可用
if (Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
// 写入SD卡
fileOutputStream=new FileOutputStream(file);
fileOutputStream.write(data, 0, data.length);
//Toast.makeText( DownLoadService.this,"下载完毕", Toast.LENGTH_LONG).show();
Toast.makeText( getApplicationContext(),"下载完毕", Toast.LENGTH_LONG).show();
}
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally { if (fileOutputStream != null) {
try {
fileOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} } }

调用服务界面:

package com.example.android_intentservice;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button; public class MainActivity extends Activity { private Button btn_intent=null;
private String url="http://www.baidu.com/img/bdlogo.gif";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn_intent=(Button)this.findViewById(R.id.button1);
btn_intent.setOnClickListener(new OnClickListener(){ @Override
public void onClick(View arg0) {
Intent intent=new Intent(MainActivity.this,DownLoadService.class);
intent.putExtra("url", url);
startService(intent); } });
} @Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
} }

demo下载地址:http://download.csdn.net/detail/u014600432/8175673

android service总结的更多相关文章

  1. android service两种启动方式

    android service的启动方式有以下两种: 1.Context.startService()方式启动,生命周期如下所示,启动时,startService->onCreate()-> ...

  2. 1、Android Studio集成极光推送(Jpush) 报错 java.lang.UnsatisfiedLinkError: cn.jpush.android.service.PushProtoco

    Android studio 集成极光推送(Jpush) (华为手机)报错, E/JPush: [JPushGlobal] Get sdk version fail![获取sdk版本失败!] W/Sy ...

  3. Android Service完全解析,关于服务你所需知道的一切(下)

    转载请注册出处:http://blog.csdn.net/guolin_blog/article/details/9797169 在上一篇文章中,我们学习了Android Service相关的许多重要 ...

  4. Android Service完全解析,关于服务你所需知道的一切(上)

    转载请注明出处:http://blog.csdn.net/guolin_blog/article/details/11952435 相信大多数朋友对Service这个名词都不会陌生,没错,一个老练的A ...

  5. android service 的各种用法(IPC、AIDL)

    http://my.oschina.net/mopidick/blog/132325 最近在学android service,感觉终于把service的各种使用场景和用到的技术整理得比较明白了,受益颇 ...

  6. Android service介绍和启动方式

    1.Android service的作用: service通常是用来处理一些耗时操作,或后台执行不提供用户交互界面的操作,例如:下载.播放音乐. 2.Android service的生命周期: ser ...

  7. Android Service初始

    一.Service概念 1.Service是一个应用程序组件 2.Service没有图像化界面 3.Service通常用来处理一些耗时比较长的操作 4.可以使用Service更新ContentProv ...

  8. Android Service与Thread的区别

    Android Service,后台,Android的后台就是指,它的运行是完全不依赖UI的.即使Activity被销毁,或者程序被关闭,只要进程还在,Service就可以继续运行.比如说一些应用程序 ...

  9. Android service binder aidl 关系

    /********************************************************************************** * Android servic ...

  10. Android Service AIDL 远程调用服务 【简单音乐播放实例】

    Android Service是分为两种: 本地服务(Local Service): 同一个apk内被调用 远程服务(Remote Service):被另一个apk调用 远程服务需要借助AIDL来完成 ...

随机推荐

  1. IOS 正则表达式匹配文本中URL位置并获取URL所在位置(解决连接中文问题)

    需求很简单,是从一段文本中匹配出其中的超链接.基本的做法就是用正则表达式去匹配.但是有这样一个问题. 网上大部分的识别URL的正则表达式url末尾有空格的情况下可以正确识别.比如这样的情况. 我是一段 ...

  2. SQL 的一些概念问答

    1.触发器的作用? 答:触发器是一中特殊的存储过程,主要是通过事件来触发而被执行的.它可以强化约束,来维护数据的完整性和一致性,可以跟踪数据库内的操作从而不允许未经许可的更新和变化.可以联级运算.如, ...

  3. linux常用命令之--用户与用户组管理命令

    linux的用户与用户组管理命令 1.用户和群组 groupadd:用于添加新的组群 其命令格式如下: groupadd [-option] 群组名 常用参数: -g GID:指定创建群组的GID(G ...

  4. 百家搜索:在网站中添加Google、百度等搜索引擎

    来源:http://www.ido321.com/1143.html 看到一些网站上添加了各种搜索引擎.如Google.百度.360.有道等,就有点好奇,这个怎么实现?研究了一各个搜索引擎怎么传送关键 ...

  5. 《锋利的Jquery第二版》读书笔记 第一章

    按照书本介绍顺序整理jquery库相关的语法.要点. window.onload与$(document).ready()功能类似,前者需要所有资源加载完毕,且不能同时编写多个:后者加载完DOM结构即执 ...

  6. EasyMock(官方资料整理)

    1.要求 EasyMock要求java1.5.0及以上版本. Objenesis (2.0+)必须在classpath中来执行class mocking. 2.使用Maven 在Maven中心库中可以 ...

  7. AHOI2013 Round2 Day2 简要题解

    第一题: 第一问可以用划分树或主席树在O(nlog2n)内做出来. 第二问可以用树状数组套主席树在O(nlog2n)内做出来. 我的代码太挫了,空间刚刚卡过...(在bzoj上) 第二题: 分治,将询 ...

  8. HDU-4750 Count The Pairs 最小生成树,并查集

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=4750 题意:Q个询问t,求在一个无向图上有多少对点(i,j)满足 i 到 j 的所有路径上的最长边的最 ...

  9. java工程师的标准

    1.技术广度方面至少要精通多门开源技术吧,研究过struts\spring\hibernate等的源码. 2.项目经验方面从头到尾跟过几个大项目,头是指需求阶段,包括需求调研.尾是指上线交付之后,包括 ...

  10. 第二百九十九天 how can I 坚持

    不是傻,就是因为人太好了,我宁愿相信是我人太好了,好吧,我就是对人都挺好,这是病吗. 昨天一起吃的饭一起AA了,挺好,这种事就得AA,玩的挺happy. 还有.感觉自己好傻,老是遇事焦虑,以后试着改变 ...