您的位置:首页 > 其它

Service的学习与深入

2016-06-16 08:12 288 查看
服务(Service)是Android中实现程序后台运行的解决方案,它非常适合用于去执行那些不需要和用户交互而且还要求长期运行的任务。服务的运行不依赖于任何用户界面,即使当程序被切换到后台,或者用户打开了另外一个应用程序,服务仍然能够保持正常运行。

注意服务并不是运行在一个独立的进程当中的,而是依赖于创建服务时所在的应用程序进程。当某个应用程序进程被杀掉时,所有依赖于该进程的服务也会停止运行。

也不要被服务的后台概念所迷惑,实际上服务并不会自动开启线程,所有的代码都是默认运行在主线程当中的。
1.定义一个服务
public class MyService extends Service {

@Override


public IBinder onBind(Intent intent) {


return null;


}


}

重写onCreate()、onStartCommand()和onDestroy()这三个方法。
onCreate()方法会在服务第一次创建的时候调用。

onStartCommand()方法会在每次服务启动的时候调用。

onDestroy()方法会在服务销毁的时候调用,回收不再使用的资源。
2.启动和停止服务
启动服务
Intent startIntent = new Intent(this,MyService.class);
startService(startIntent); //
启动服务
停止服务

Intent stopIntent =new Intent(this, MyService.class);
stopService(stopIntent);//
停止服务
Service 与 Thread
的区别


很多时候,你可能会问,为什么要用Service,而不用Thread
呢,因为用Thread
是很方便的,比起Service
也方便多了,下面我详细的来解释一下。

1). Thread:Thread是程序执行的最小单元,它是分配CPU的基本单位。可以用
Thread 来执行一些异步的操作。

2). Service:Service是android的一种机制,当它运行的时候如果是LocalService,那么对应的Service
是运行在主进程的 main
线程上的。如:onCreate,onStart
这些函数在被系统调用的时候都是在主进程的 main
线程上运行的。如果是Remote Service,那么对应的 Service
则是运行在独立进程的 main
线程上。

Service与Activity通信:

Service后端的数据最终还是要呈现在前端Activity之上的,因为启动Service时,系统会重新开启一个新的进程,这就涉及到不同进程间通信的问题了(AIDL),当我们想获取启动的Service实例时,我们可以用到bindService和onBindService方法,它们分别执行了Service中IBinder()和onUnbind()方法。

通常每个应用程序都在它自己的进程内运行,但有时需要在进程间传递对象,你可以通过应用程序UI的方式写个运行在一个不同的进程中的service。

在android平台中,一个进程通常不能访问其他进程中的内存区域。所以,他们需要把对象拆分成操作系统能理解的简单形式,以便伪装成对象跨越边界访问。编写这种伪装代码相当的枯燥乏味,好在android为我们提供了AIDL工具可以来做这件事.

拓展深入
AndroidService的生命周期

service的生命周期,从它被创建开始,到它被销毁为止,可以有两条不同的路径:

A started service

  被开启的service通过其他组件调用 startService()被创建。

  这种service可以无限地运行下去,必须调用stopSelf()方法或者其他组件调用stopService()方法来停止它。

  当service被停止时,系统会销毁它。

下面的service展示了每一个生命周期的方法:
public class ExampleService extends Service

{

intmStartMode; // indicates how to behave if the service is killed

IBinder mBinder; // interface for clients that bind

boolean mAllowRebind; // indicates whether onRebind should be used

@Override

public void onCreate()

{

// The service is being created

}

@Override

public int onStartCommand(Intent intent, int flags, int startId)

{

// The service is starting, due to a call to startService()

return mStartMode;

}

@Override

public IBinder onBind(Intent intent)

{

// A client is binding to the service with bindService()

return mBinder;

}

@Override

public boolean onUnbind(Intent intent)

{

// All clients have unbound with unbindService()

return mAllowRebind;

}

@Override

public void onRebind(Intent intent)

{

// A client is binding to the service with bindService(),

// after onUnbind() has already been called

}

@Override

public void onDestroy()

{

// The service is no longer used and is being destroyed

}

}


Theentire lifetime
service整体的生命时间是从[b]onCreate()[/b]被调用开始,到[b]onDestroy()[/b]方法返回为止。
  和activity一样,service在[b]onCreate()[/b]中进行它的初始化工作,在[b]onDestroy()[/b]中释放残留的资源。
  比如,一个音乐播放service可以在onCreate()中创建播放音乐的线程,在onDestory()中停止这个线程。
onCreate()onDestroy()会被所有的service调用,不论service是通过startService()还是bindService()建立。

service积极活动的生命时间(activelifetime)是从onStartCommand()onBind()被调用开始,它们各自处理由startService()bindService()方法传过来的Intent对象。
  如果service是被开启的,那么它的活动生命周期和整个生命周期一同结束。
  如果service是被绑定的,它们它的活动生命周期是在onUnbind()方法返回后结束。
注意:尽管一个被开启的service是通过调用 stopSelf()stopService()来停止的,没有一个对应的回调函数与之对应,即没有onStop()回调方法。所以,当调用了停止的方法,除非这个service和客户组件绑定,否则系统将会直接销毁它,onDestory()方法会被调用,并且是这个时候唯一会被调用的回调方法。
示例
main.xml代码
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content" android:id="@+id/btnStartMyService"
android:text="StartMyService"></Button>
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content" android:id="@+id/btnStopMyService"
android:text="StopMyService"></Button>
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content" android:id="@+id/btnBindMyService"
android:text="BindMyService"></Button>
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content" android:id="@+id/btnUnbindMyService"
android:text="UnbindMyService"></Button>
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content" android:id="@+id/btnExit"
android:text="退出程序"></Button>
</LinearLayout>
testService.java的源码如下:

package com.testService;

import android.app.Activity;
import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.widget.Button;

public class testService extends Activity {
Button btnStartMyService,btnStopMyService,btnBindMyService,btnUnbindMyService,btnExit;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btnStartMyService=(Button)this.findViewById(R.id.btnStartMyService);
btnStartMyService.setOnClickListener(new ClickEvent());

btnStopMyService=(Button)this.findViewById(R.id.btnStopMyService);
btnStopMyService.setOnClickListener(new ClickEvent());

btnBindMyService=(Button)this.findViewById(R.id.btnBindMyService);
btnBindMyService.setOnClickListener(new ClickEvent());

btnUnbindMyService=(Button)this.findViewById(R.id.btnUnbindMyService);
btnUnbindMyService.setOnClickListener(new ClickEvent());

btnExit=(Button)this.findViewById(R.id.btnExit);
btnExit.setOnClickListener(new ClickEvent());
}
@Override
public void onDestroy()
{
super.onDestroy();
Log.e("Activity","onDestroy");
}

private ServiceConnection _connection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName arg0, IBinder arg1) {
// TODO Auto-generated method stub
}

@Override
public void onServiceDisconnected(ComponentName name) {
// TODO Auto-generated method stub
}
};
class ClickEvent implements View.OnClickListener{

@Override
public void onClick(View v) {
Intent intent=new Intent(testService.this,MyService.class);
if(v==btnStartMyService){
testService.this.startService(intent);
}
else if(v==btnStopMyService){
testService.this.stopService(intent);
}
else if(v==btnBindMyService){
testService.this.bindService(intent, _connection, Service.BIND_AUTO_CREATE);
}
else if(v==btnUnbindMyService){
if(MyService.ServiceState=="onBind")//Service绑定了之后才能解绑
testService.this.unbindService(_connection);
}
else if(v==btnExit)
{
testService.this.finish();
}

}

}
}
MyService.java的源码如下:
package com.testService;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

public class MyService extends Service {
static public String ServiceState="";
@Override
public IBinder onBind(Intent arg0) {
Log.e("Service", "onBind");
ServiceState="onBind";
return null;
}
@Override
public boolean onUnbind(Intent intent){
super.onUnbind(intent);
Log.e("Service", "onUnbind");
ServiceState="onUnbind";
return false;

}
@Override
public void onCreate(){
super.onCreate();
Log.e("Service", "onCreate");
ServiceState="onCreate";
}
@Override
public void onDestroy(){
super.onDestroy();
Log.e("Service", "onDestroy");
ServiceState="onDestroy";
}
@Override
public void onStart(Intent intent,int startid){
super.onStart(intent, startid);
Log.e("Service", "onStart");
ServiceState="onStart";
}

}


参考资料

API Guides:Services

API Guides:Bound Services


http://www.android-study.net/


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: