android service总结
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总结的更多相关文章
- android service两种启动方式
android service的启动方式有以下两种: 1.Context.startService()方式启动,生命周期如下所示,启动时,startService->onCreate()-> ...
- 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 ...
- Android Service完全解析,关于服务你所需知道的一切(下)
转载请注册出处:http://blog.csdn.net/guolin_blog/article/details/9797169 在上一篇文章中,我们学习了Android Service相关的许多重要 ...
- Android Service完全解析,关于服务你所需知道的一切(上)
转载请注明出处:http://blog.csdn.net/guolin_blog/article/details/11952435 相信大多数朋友对Service这个名词都不会陌生,没错,一个老练的A ...
- android service 的各种用法(IPC、AIDL)
http://my.oschina.net/mopidick/blog/132325 最近在学android service,感觉终于把service的各种使用场景和用到的技术整理得比较明白了,受益颇 ...
- Android service介绍和启动方式
1.Android service的作用: service通常是用来处理一些耗时操作,或后台执行不提供用户交互界面的操作,例如:下载.播放音乐. 2.Android service的生命周期: ser ...
- Android Service初始
一.Service概念 1.Service是一个应用程序组件 2.Service没有图像化界面 3.Service通常用来处理一些耗时比较长的操作 4.可以使用Service更新ContentProv ...
- Android Service与Thread的区别
Android Service,后台,Android的后台就是指,它的运行是完全不依赖UI的.即使Activity被销毁,或者程序被关闭,只要进程还在,Service就可以继续运行.比如说一些应用程序 ...
- Android service binder aidl 关系
/********************************************************************************** * Android servic ...
- Android Service AIDL 远程调用服务 【简单音乐播放实例】
Android Service是分为两种: 本地服务(Local Service): 同一个apk内被调用 远程服务(Remote Service):被另一个apk调用 远程服务需要借助AIDL来完成 ...
随机推荐
- 陈发树云南白药股权败诉真相 取胜仅差三步 z
22亿元现金,三年只拿到750多万元的利息.福建富豪陈发树的云南生意可谓失望之极.在漫长的官司中,曾经有绝处逢生之机的陈发树,连告状的主体都没有找准,岂能同强大的国企扳手腕?陈发树律师团距取胜只有三步 ...
- 如何解决Rally模板提示angular js加载错误
[前言] Rally是一个开源测试工具,用于测试openstack各个组件的性能 在使用Rally测试完毕后,一般会生成测试报告,这点很重要.但是原生态的Rally报告模板angular js框架是从 ...
- Libsvm的MATLAB调用和交叉验证
今天听了一个师兄的讲课,才发现我一直在科研上特别差劲,主要表现在以下几个方面,(现在提出也为了督促自己在以后的学习工作道路上能够避免这些问题) 1.做事情总是有头无尾,致使知识点不能一次搞透,每次在用 ...
- <转>DNS服务系列之二:DNS区域传送漏洞的安全案例
DNS区域传送(DNS zone transfer)指的是一台备用服务器使用来自主服务器的数据刷新自己的域(zone)数据库.这为运行中的DNS服务提供了一定的冗余度,其目的是为了防止主的域名服务器因 ...
- ASP.NET MVC之Html.RenderAction
WEB窗体模式开发惯了,切入MVC模式,好多东西都不懂,每一步都要查资料. 初步得来的一些知识点体会是: _Layout.cshtml就相当于母版页 然后partical视图(部分视图)就是用户控件. ...
- [HIve - LanguageManual] Transform [没懂]
Transform/Map-Reduce Syntax SQL Standard Based Authorization Disallows TRANSFORM TRANSFORM Examples ...
- 最全面的 MySQL 索引详解
什么是索引? 1.索引 索引是表的目录,在查找内容之前可以先在目录中查找索引位置,以此快速定位查询数据.对于索引,会保存在额外的文件中. 2.索引,是数据库中专门用于帮助用户快速查询数据的一种数据结构 ...
- 第二百八十六天 how can I 坚持
bug不断啊,头疼. 今天早上到的倒是挺早. 中午吃的黄焖鸡,晚上加了会班. 勇江的鱼都死了,杨建的还剩3条,晚上到家都快十点了,还洗了衣服,没捞出来呢, 希望可以请下来假吧. 晾上衣服睡觉.
- work7
uno. 理解C++变量的作用域和生命周期 没有要求讲解我就简单注释了一下~ #include <iostream>int main(){ for (int i=0;i<10;i++ ...
- oracle 全文检索技术
1.查看用户: select * from dba_users WHERE username='CTXSYS';select * from dba_users WHERE username='CTXS ...