Android Service组件在后台不可见,但一般情况下是与其他组件一同运行在一个进程中的(Local Service与其他部分在一个进程,Remote Service单独开进程),而且在主线程中,并不单独启动一个线程(除非程序员自己另外开线程)
Service组件提供了后台执行某些功能以及为其他应用程序提供服务,提供支撑功能的能力。
生命周期:OnCreate()->OnStartCommand()->OnDestroy()。
调用 Context.startService()可以多次调用,但只要调用stopService一次就会stop.多次调用startService或者bindService不会启动多个服务。
local service样例
public class LocalService extends Service {
private NotificationManager mNM;
// Unique Identification Number for the Notification.
// We use it on Notification start, and to cancel it.
private int NOTIFICATION = R.string.local_service_started;
/**
* Class for clients to access. Because we know this service always
* runs in the same process as its clients, we don't need to deal with
* IPC.
*/
public class LocalBinder extends Binder {
LocalService getService() {
return LocalService.this;
}
}
@Override
public void onCreate() {
mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
// Display a notification about us starting. We put an icon in the status bar.
showNotification();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i("LocalService", "Received start id " + startId + ": " + intent);
// We want this service to continue running until it is explicitly
// stopped, so return sticky.
return START_STICKY;
}
@Override
public void onDestroy() {
// Cancel the persistent notification.
mNM.cancel(NOTIFICATION);
// Tell the user we stopped.
Toast.makeText(this, R.string.local_service_stopped, Toast.LENGTH_SHORT).show();
}
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
// This is the object that receives interactions from clients. See
// RemoteService for a more complete example.
private final IBinder mBinder = new LocalBinder();
/**
* Show a notification while this service is running.
*/
private void showNotification() {
// In this sample, we'll use the same text for the ticker and the expanded notification
CharSequence text = getText(R.string.local_service_started);
// Set the icon, scrolling text and timestamp
Notification notification = new Notification(R.drawable.stat_sample, text,
System.currentTimeMillis());
// The PendingIntent to launch our activity if the user selects this notification
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, LocalServiceActivities.Controller.class), 0);
// Set the info for the views that show in the notification panel.
notification.setLatestEventInfo(this, getText(R.string.local_service_label),
text, contentIntent);
// Send the notification.
mNM.notify(NOTIFICATION, notification);
}
}
调用
private LocalService mBoundService;
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
// This is called when the connection with the service has been
// established, giving us the service object we can use to
// interact with the service. Because we have bound to a explicit
// service that we know is running in our own process, we can
// cast its IBinder to a concrete class and directly access it.
mBoundService = ((LocalService.LocalBinder)service).getService();
// Tell the user about this for our demo.
Toast.makeText(Binding.this, R.string.local_service_connected,
Toast.LENGTH_SHORT).show();
}
public void onServiceDisconnected(ComponentName className) {
// This is called when the connection with the service has been
// unexpectedly disconnected -- that is, its process crashed.
// Because it is running in our same process, we should never
// see this happen.
mBoundService = null;
Toast.makeText(Binding.this, R.string.local_service_disconnected,
Toast.LENGTH_SHORT).show();
}
};
void doBindService() {
// Establish a connection with the service. We use an explicit
// class name because we want a specific service implementation that
// we know will be running in our own process (and thus won't be
// supporting component replacement by other applications).
bindService(new Intent(Binding.this,
LocalService.class), mConnection, Context.BIND_AUTO_CREATE);
mIsBound = true;
}
void doUnbindService() {
if (mIsBound) {
// Detach our existing connection.
unbindService(mConnection);
mIsBound = false;
}
}
@Override
protected void onDestroy() {
super.onDestroy();
doUnbindService();
}
在Activity中通过mBoundService调用Service中的public方法来获取后台数据,实际上onServiceConnected中返回的是一个IBinder对象,只不过我们在此已经确定Local Service
已经在执行了,可以进行强制类型转换。
Local Service可以通过发送广播来给前台提供后台数据更新,前台只需要注册一个Receiver既可以与Service通讯。
例子:
后台Service的某个方法进行数据更新后执行
Intent intent = new Intent("XXXX_Message");
sendBroadcast(intent); 通知前台数据已经更新
前台
private MessageReceiver receiver;
class MessageReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context arg0, Intent arg1) {
String action = arg1.getAction();
if (action.equals("XXXX_Message")) {
//从Service接收广播消息
String msgStr = arg1.getStringExtra("msg_str");
}
}
}
@Override
protected void onResume() {
super.onResume();
IntentFilter filter = new IntentFilter("XXXX_Message");
if (receiver == null)
receiver = new MessageReceiver();
//注册BroadcastReceiver
registerReceiver(receiver, filter);
}
@Override
protected void onPause() {
unregisterReceiver(receiver);
super.onPause();
}
分享到:
相关推荐
Android Upload Service Easily upload files in the background with automatic Android Notification Center progress indication. Download the latest demo app APK which uses the library and try it ...
安卓app开发项目-LumaQQ-Android qq 代码(源码).zip安卓app开发项目-LumaQQ-Android qq 代码(源码).zip安卓app开发项目-LumaQQ-Android qq 代码(源码).zip安卓app开发项目-LumaQQ-Android qq 代码(源码).zip安卓app...
《移动应用开发》小组项目-Android 音乐播放器项目源码《移动应用开发》小组项目-Android 音乐播放器项目源码《移动应用开发》小组项目-Android 音乐播放器项目源码《移动应用开发》小组项目-Android 音乐播放器项目...
Android Service下载文件
Android---Service Timer之执行周期任务
ksoap2-android-assembly-2.6.5-jar-with-dependencies.jar 要是需要最新的,下载地址: http://code.google.com/p/ksoap2-android/
Android-android-upload-service.zip,在后台轻松上载文件(ftp/multipart/binary),并提供进度指示通知,安卓系统是谷歌在2008年设计和制造的。操作系统主要写在爪哇,C和C 的核心组件。它是在linux内核之上构建的,...
rk-android9.0-root补丁(rootservice方式).rar
安卓app开发项目-联想Android开发工程师面试题(源码).zip安卓app开发项目-联想Android开发工程师面试题(源码).zip安卓app开发项目-联想Android开发工程师面试题(源码).zip安卓app开发项目-联想Android开发工程师面试...
淮海工学院计算机工程学院 开放实验... " ----------------------- 《Android应用开发》开放实验项目总结报告-模板全文共2页,当前为第1页。 《Android应用开发》开放实验项目总结报告-模板全文共2页,当前为第2页。
在Android平台调用Web Service需要依赖于第三方类库ksoap2,它是一个SOAP Web service客户端开发包。此jar包用于android和webservice进行通信,目前版本3.6.2
Android开发-Volley-解析Json使用方法-完整Demo-AndroidStudio http://blog.csdn.net/iwanghang/article/details/52241233
[经典文档]Android核心分析 核心分析之一 ----- 分析方法论探讨之设计意图 核心分析之二 ----- 方法论探讨之概念空间篇 核心分析之三 ----- 手机之硬件形态 核心分析之四 ----- 手机之软件形态 核心分析之五 ----- ...
安卓发送Exchange邮件,引用ews-android-api.jar和joda-time-2.8.jar两个包。 用法: ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP2); ExchangeCredentials credentials = new ...
Android核心分析(07)----Service深入分析 Android核心分析(08)----Android 启动过程详解 Android核心分析(09)----Zygote Service Android核心分析(10)----Android GWES之基本原理篇 Android核心分析(11)--...
android 有关service的应用
android,启动service,并且service把值传给Activity显示
关于ANR原理的透彻总结,简单易懂
一组快速启动示例,演示Android上的FireBase API。有关更多信息,请参见https://firebase.google.com。