关于Android Service组件在多线程应用的理解

Android Service组件在Google Android SDK官网上的定义是这样的:

A Service is an application component representing either an application's desire to perform a longer-running operation while not interacting with the user or to supply functionality for other applications to use. Each service class must have a corresponding declaration in its package's AndroidManifest.xml. Services can be started with Context.startService() and Context.bindService().

Note that services, like other application objects, run in the main thread of their hosting process. This means that, if your service is going to do any CPU intensive (such as MP3 playback) or blocking (such as networking) operations, it should spawn its own thread in which to do that work. More information on this can be found in Processes and Threads. The IntentService class is available as a standard implementation of Service that has its own thread where it schedules its work to be done.

在中文中,他的表述是服务。Android赋予了Service比处于不活动状态的活动更高的优先级,这样,在系统请求资源的时候,他们被终止的可能行更小。事实上,如果运行时过早的终止一个已启动的服务,那么只要有足够的资源可用,则运行时就会重新启动它。在极端情况中,服务的终止将会显著的影响用户体验,从而导致软件设计上的UI与UE的互动缺失,在这些情况中,可以把服务的优先级提升到与前台的活动相同的位置。通过使用服务,可以保证应用程序持续的运行,并对事件作出响应,即使他们被主动地使用也是此。

Service运行时没有专门的GUI,但是,与活动以及广播接收器一样,他们仍然应该在应用程序进程的主进程执行。下面将为大家简要介绍一下Android中使用Java进线程调用的使用方法。

1.创建一个线程
[java] view plaincopy

/**
* @Copyright by Alfred Z.Zheng, Cindigo. 2011-09. Wuhan.
* An innovative club in Huazhong Univ. of Sci. & Tech.
* Prj. name: org.cindigo.javatestthread1
*/
class Mythread implements Runnable{
//Mythread实现了Runnable
int count;
String thrdName;

Mythread(String name){
count = 0;
thrdName = name;
}
public void run(){
//线程运行起点
System.out.println(thrdName + "start a thread.");
try{
do{
Thread.sleep(1000);
System.out.println("@At " + thrdName + ", result is " + count);
count++;
} while(count < 10);
}
catch(InterruptException exc){
System.out.println(thrdName + " interrupted.");
}
System.out.println(thrdName + " timing up!");
}
}
class UseThreads{
public static void main(String args[]){
System.out.println("Starting a main thread...");

//创建一个可运行的对象
MyThread myth = new MyThread("Activity No.1");

//在该对象上构造一个线程
Thread newth = new Thread(myth);
newth.start();

do{
System.out.println("Activity No.2");
try{
Thread.sleep(500);
}catch(InterruptException exc){
System.out.println("Activity No.3");
}
}while(myth.count != 10);

System.out.println("Activity No.4");
}
}

2.创建多个线程

[java] view plaincopy

/**
* @Copyright by Alfred Z.Zheng, Cindigo. 2011-09. Wuhan.
* An innovative club in Huazhong Univ. of Sci. & Tech.
* Prj. name: org.cindigo.javatestthread2
*/
//创建多重线程
class MyThread implements Runnable{
int count;
Thread thrd;

//建立新线程
MyThread(String name){
thrd = new Thread(this, name);
count = 0;
thrd.start(); //开启线程
}
//开启新的主线程
public void run(){
System.out.println(thrd.getName() + " starting.");
try{
do{
Thread.sleep(500);
System.out.println("In " + thrd.getName() + ", count is " + count);
count++;
}while(count < 10);
}
catch(InterruptException exc){
System.out.println(thrd.getName() + " interrupted.");
}
System.out.println(thrd.getName() + " timing up!");
}
}
class UseThreadsImpoved{
public static void main(String arg[]{

System.out.println("Main thread starting.");
//现在线程在创建时启动
Mythread myth = new MyThread("My Activity No.1");
do{
System.out.println(".");
try{
Thread.sleep(1000);
}
catch(InterruptException exc){
System.out.println("My Activity No.2");
}
}while(myth.count != 10);
System.out.println("My Activity No.2");
}
}

下面为大家讲一下Android Service组件的创建并初步的使用的方法。首先为大家简要介绍一下Service的生命周期。

onBind(Intent intent):是Service实现功能的最重要的方法,调用时会返回一个绑定的接口给Service。

onCreate():当Service初次创建时被系统自动调用。

onStart(Intent intent, int startid):当startService()方法启动Service时,这个方法会被自动调用。

onDestroy():终止Service时,系统会调用这个方法。

1.创建一个Service

[java] view plaincopy

/**
*@Copyright® Cindigo, HUST, Wuhan.
*Prj.:org.cindigo.jetaime
*/

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

public class MyService extends Service{

private static final String TAG = "CONNECTION";
private static final boolean Judge = true;

public IBinder onBind(Intent intent){
Log.i(TAG, "Bind Success!");
}

@Override
public void onCreate(){
Toast.makeText(this, "My Service Created", Toast.LENGTH_SHORT).show();
if (Judge)
Log.d(TAG, "onCreate");
}

@Override
public void onStart(Intent intent, int startid){
Toast.makeText(this, "My Service Started", Toast.LENGTH_SHORT).show();
if (Judge)
Log.d(TAG, "onStart");
}

@Override
public void onDestroy(){
Toast.makeText(this, "My Service Stopped", Toast.LENGTH_SHORT).show();
if (Judge)
Log.d(TAG, "onDestroy");
}
}

2.启动和停止线程

[java] view plaincopy

/**
*@Copyright® Cindigo, HUST, Wuhan.
*Prj.:org.cindigo.jetaime
*/

import android.app.Service;
import android.content.Intent;

//创建一个Intent
Intent intent = new Intent();

//设置动作属性
intent.setAction("logging 1...");

//启动这个Service
startService(intent);

//终止一个Service
stopService(intent);

3.绑定和解绑一个已存在的Service
[java] view plaincopy

/**
*@Copyright® Cindigo, HUST, Wuhan.
*Prj.:org.cindigo.jetaime
*/

import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;

public void BindService(){//绑定服务
if (!mIsBound) {
bindService(new Intent(this,
ConnectService.class), mConnection, Context.BIND_AUTO_CREATE);
mIsBound = true;
}
}
public void UnbindService(){//解绑服务
if (mIsBound) {
unbindService(mConnection);
mIsBound = false;
}
}
private ServiceConnection mConnection = new ServiceConnection(){//服务连接对象
public void onServiceConnected(ComponentName className, IBinder service) {
mConnectService = ((ConnectService.LocalBinder)service).getService();//获得已绑定的服务
mConnectService.GetServer(LOGON_HOST, LOGON_PORT);
mConnectService.connect();
}
public void onServiceDisconnected(ComponentName className) {
mConnectService = null;
Log.i("Q", "EEE");
}
}

4.应用实例(参考《Android应用开发详解》)

4.1MainActivity.java文件

[java] view plaincopy

/**
*@Copyright® Cindigo, HUST, Wuhan.
*Prj.:org.cindigo.jetaime
*/

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.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {
// 声明Button
private Button startBtn,stopBtn,bindBtn,unbindBtn;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// 设置当前布局视图
setContentView(R.layout.main);
// 实例化Button
startBtn = (Button)findViewById(R.id.startButton01);
stopBtn = (Button)findViewById(R.id.stopButton02);
bindBtn = (Button)findViewById(R.id.bindButton03);
unbindBtn = (Button)findViewById(R.id.unbindButton04);

// 添加监听器
startBtn.setOnClickListener(startListener);
stopBtn.setOnClickListener(stopListener);
bindBtn.setOnClickListener(bindListener);
unbindBtn.setOnClickListener(unBindListener);

}
// 启动Service监听器
private OnClickListener startListener = new OnClickListener() {
@Override
public void onClick(View v) {
// 创建Intent
Intent intent = new Intent();
// 设置Action属性
intent.setAction("com.amaker.ch07.app.action.MY_SERVICE");
// 启动该Service
startService(intent);
}
};

// 停止Service监听器
private OnClickListener stopListener = new OnClickListener() {
@Override
public void onClick(View v) {
// 创建Intent
Intent intent = new Intent();
// 设置Action属性
intent.setAction("com.amaker.ch07.app.action.MY_SERVICE");
// 启动该Service
stopService(intent);
}
};

// 连接对象
private ServiceConnection conn = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
Log.i("SERVICE", "连接成功!");
Toast.makeText(MainActivity.this, "连接成功!", Toast.LENGTH_LONG).show();
}
@Override
public void onServiceDisconnected(ComponentName name) {
Log.i("SERVICE", "断开连接!");
Toast.makeText(MainActivity.this, "断开连接!", Toast.LENGTH_LONG).show();
}
};

// 綁定Service监听器
private OnClickListener bindListener = new OnClickListener() {
@Override
public void onClick(View v) {
// 创建Intent
Intent intent = new Intent();
// 设置Action属性
intent.setAction("com.amaker.ch07.app.action.MY_SERVICE");

// 绑定Service
bindService(intent, conn, Service.BIND_AUTO_CREATE);
}
};

// 解除绑定Service监听器
private OnClickListener unBindListener = new OnClickListener() {
@Override
public void onClick(View v) {
// 创建Intent
Intent intent = new Intent();
// 设置Action属性
intent.setAction("com.amaker.ch07.app.action.MY_SERVICE");
// 解除绑定Service
unbindService(conn);
}
};

}

4.2MyService.java文件

[java] view plaincopy

/**
*@Copyright® Cindigo, HUST, Wuhan.
*Prj.:org.cindigo.jetaime
*/

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

/**
* @author 郭宏志
* 测试Service
*/
public class MyService extends Service{

// 可以返回null,通常返回一个有aidl定义的接口
public IBinder onBind(Intent intent) {
Log.i("SERVICE", "onBind.");
Toast.makeText(MyService.this, "onBind.", Toast.LENGTH_LONG).show();
return null;
}
// Service创建时调用
public void onCreate() {
Log.i("SERVICE", "onCreate.");
Toast.makeText(MyService.this, "onCreate.", Toast.LENGTH_LONG).show();
}
// 当客户端调用startService()方法启动Service时,该方法被调用
public void onStart(Intent intent, int startId) {
Log.i("SERVICE", "onStart.");
Toast.makeText(MyService.this, "onStart.", Toast.LENGTH_LONG).show();
}
// 当Service不再使用时调用
public void onDestroy() {
Log.i("SERVICE", "onDestroy.");
Toast.makeText(MyService.this, "onDestroy.", Toast.LENGTH_LONG).show();
}
}
有关编译器优化的更完整信息,请参阅优化通知