service使用以及startService,stopService,bindService,unbindService方法比较

Service概述

由于手机屏幕的限制,通常情况下在同一时刻仅有一个应用程序处于激活状态,并能够显示在手机屏幕上,因此,应用程序需要一种机制,在没有用户界面的情况下,能够长时间在后台运行,实现应用程序的特定功能,并能够处理事件或更新数据.Android系统提供了(Service)服务组件,它不直接与用户进行交互,却能够长期在后台运行。有很多情况需要使用Service,典型的例子就是:MP3播放器。

Service非常适用于无需用户干预,且需要长期运行的后台功能。Service没有用户界面,有利于降低系统资源。而且Service比Activity具有更高的优先级,只有在系统资源极度匮乏的情况下,android系统才可能清理掉一部分service来保证系统的运行,而这种情况却又轻易不会出现。即使Service被系统终止了,在系统资源恢复后Service也将自动恢复运行状态,因此可以认为Service是在系统中永久运行的组件。Service除了实现后台服务功能,还可以用于进程间通信,解决两个不同Activity应用程序进程之间的调用和通信问题。

Service的生命周期如下图所示:


下面我们用简单地例子来讲解一下如何启动Service

界面如下图所示


实现该界面的xml文件的代码如下:

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="fill_parent"  
  4.     android:layout_height="fill_parent"  
  5.     android:orientation="vertical" >  
  6.   
  7.     <TextView  
  8.         android:layout_width="fill_parent"  
  9.         android:layout_height="wrap_content"  
  10.         android:text="@string/hello" />  
  11.   
  12.     <Button  
  13.         android:id="@+id/start"  
  14.         android:layout_width="wrap_content"  
  15.         android:layout_height="wrap_content"  
  16.         android:text="startService" />  
  17.   
  18.     <Button  
  19.         android:id="@+id/stop"  
  20.         android:layout_width="wrap_content"  
  21.         android:layout_height="wrap_content"  
  22.         android:text="stopService" />  
  23.   
  24.     <Button  
  25.         android:id="@+id/bind"  
  26.         android:layout_width="wrap_content"  
  27.         android:layout_height="wrap_content"  
  28.         android:text="bindService" />  
  29.   
  30.   
  31.     <Button  
  32.         android:id="@+id/unbind"  
  33.         android:layout_width="wrap_content"  
  34.         android:layout_height="wrap_content"  
  35.         android:text="unBindService" />  
  36.   
  37. </LinearLayout>  
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />

    <Button
        android:id="@+id/start"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="startService" />

    <Button
        android:id="@+id/stop"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="stopService" />

    <Button
        android:id="@+id/bind"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="bindService" />


    <Button
        android:id="@+id/unbind"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="unBindService" />

</LinearLayout>

Activity的代码如下:

  1. package com.yongchun.intent.ui;  
  2.   
  3. /* 
  4.  * bindService和startService都是启动Service,有什么地方不一样呢: 
  5.  *  
  6.  * 1. startService Service中使用StartService()方法来进行方法的调用,调用者和服务之间没有联系, 
  7.  * 即使调用者退出了,服务依然在进行 
  8.  * 【onCreate()->onStartCommand()->startService()->onDestroy()】, 
  9.  * 注意其中没有onStart(),主要是被onStartCommand()方法给取代了,onStart方法不推荐使用了。 
  10.  * ###################################################################### 
  11.  * 2. bindService中使用bindService()方法来绑定服务,调用者和绑定者绑在一起, 调用者一旦退出服务也就终止了 
  12.  * 【onCreate()->onBind()->onUnbind()->onDestroy()】。 
  13.  *  
  14.  * 鱼说:简而言之,我们做个最简单的测试 第一步:使用startService()启动服务播放音乐,退出应用程序后,音乐还在播放. 
  15.  * 第二步:使用bindService()启动服务播放音乐,退出应用程序后,音乐的播放也随之停止了. 
  16.  */  
  17. import android.app.Activity;  
  18. import android.content.ComponentName;  
  19. import android.content.Intent;  
  20. import android.content.ServiceConnection;  
  21. import android.os.Bundle;  
  22. import android.os.IBinder;  
  23. import android.view.View;  
  24. import android.view.View.OnClickListener;  
  25.   
  26. public class MainActivity extends Activity implements OnClickListener {  
  27.     /** Called when the activity is first created. */  
  28.     @Override  
  29.     public void onCreate(Bundle savedInstanceState) {  
  30.         super.onCreate(savedInstanceState);  
  31.         // 加载布局文件   
  32.         setContentView(R.layout.main);  
  33.         // 获取对控件的引用,并设置监听   
  34.         findViewById(R.id.start).setOnClickListener(this);  
  35.         findViewById(R.id.stop).setOnClickListener(this);  
  36.         findViewById(R.id.bind).setOnClickListener(this);  
  37.         findViewById(R.id.unbind).setOnClickListener(this);  
  38.     }  
  39.   
  40.     // 创建一个 ServiceConnection 对象   
  41.     final ServiceConnection connection = new ServiceConnection() {  
  42.   
  43.         public void onServiceDisconnected(ComponentName name) {  
  44.             // TODO Auto-generated method stub   
  45.   
  46.         }  
  47.   
  48.         public void onServiceConnected(ComponentName name, IBinder service) {  
  49.             // TODO Auto-generated method stub   
  50.   
  51.         }  
  52.     };  
  53.   
  54.     // 监听事件   
  55.     public void onClick(View v) {  
  56.         // TODO Auto-generated method stub   
  57.         Intent intent = new Intent(MainActivity.this, PlayRadioService.class);  
  58.         switch (v.getId()) {  
  59.         // startService()方法开启服务   
  60.         case R.id.start:  
  61.             startService(intent);  
  62.             break;  
  63.   
  64.         // stopService()方法停止服务   
  65.         case R.id.stop:  
  66.             stopService(intent);  
  67.             break;  
  68.   
  69.         // bindService()方法开启服务   
  70.         case R.id.bind:  
  71.             bindService(intent, connection, BIND_AUTO_CREATE);  
  72.             break;  
  73.   
  74.         // unbindService()方法停止服务   
  75.         case R.id.unbind:  
  76.             unbindService(connection);  
  77.             break;  
  78.   
  79.         default:  
  80.             break;  
  81.         }  
  82.   
  83.     }  
  84. }  
package com.yongchun.intent.ui;

/*
 * bindService和startService都是启动Service,有什么地方不一样呢:
 * 
 * 1. startService Service中使用StartService()方法来进行方法的调用,调用者和服务之间没有联系,
 * 即使调用者退出了,服务依然在进行
 * 【onCreate()->onStartCommand()->startService()->onDestroy()】,
 * 注意其中没有onStart(),主要是被onStartCommand()方法给取代了,onStart方法不推荐使用了。
 * ######################################################################
 * 2. bindService中使用bindService()方法来绑定服务,调用者和绑定者绑在一起, 调用者一旦退出服务也就终止了
 * 【onCreate()->onBind()->onUnbind()->onDestroy()】。
 * 
 * 鱼说:简而言之,我们做个最简单的测试 第一步:使用startService()启动服务播放音乐,退出应用程序后,音乐还在播放.
 * 第二步:使用bindService()启动服务播放音乐,退出应用程序后,音乐的播放也随之停止了.
 */
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.view.View;
import android.view.View.OnClickListener;

public class MainActivity extends Activity implements OnClickListener {
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// 加载布局文件
		setContentView(R.layout.main);
		// 获取对控件的引用,并设置监听
		findViewById(R.id.start).setOnClickListener(this);
		findViewById(R.id.stop).setOnClickListener(this);
		findViewById(R.id.bind).setOnClickListener(this);
		findViewById(R.id.unbind).setOnClickListener(this);
	}

	// 创建一个 ServiceConnection 对象
	final ServiceConnection connection = new ServiceConnection() {

		public void onServiceDisconnected(ComponentName name) {
			// TODO Auto-generated method stub

		}

		public void onServiceConnected(ComponentName name, IBinder service) {
			// TODO Auto-generated method stub

		}
	};

	// 监听事件
	public void onClick(View v) {
		// TODO Auto-generated method stub
		Intent intent = new Intent(MainActivity.this, PlayRadioService.class);
		switch (v.getId()) {
		// startService()方法开启服务
		case R.id.start:
			startService(intent);
			break;

		// stopService()方法停止服务
		case R.id.stop:
			stopService(intent);
			break;

		// bindService()方法开启服务
		case R.id.bind:
			bindService(intent, connection, BIND_AUTO_CREATE);
			break;

		// unbindService()方法停止服务
		case R.id.unbind:
			unbindService(connection);
			break;

		default:
			break;
		}

	}
}

Activity的开头部分详细介绍了startService以及bindService用法的区别,这里不再累述。


接下来是Service的代码:


  1. package com.yongchun.intent.ui;  
  2.   
  3. import android.app.Service;  
  4. import android.content.Intent;  
  5. import android.media.MediaPlayer;  
  6. import android.os.IBinder;  
  7. import android.util.Log;  
  8.   
  9. /** 
  10.  * 作者:肥鱼 QQ群:104780991 Email:zhaoyongchun2011@gmail.com 
  11.  * 关于:一条致力于Android开源事业的鱼,还是肥的.吃得多赚的少还不会暖床,求包养. 
  12.  */  
  13. public class PlayRadioService extends Service {  
  14.   
  15.     private MediaPlayer player;  
  16.   
  17.     @Override  
  18.     public void onCreate() {  
  19.         // TODO Auto-generated method stub   
  20.         Log.v("PlayRadioSevice""Service onCreat()执行成功");  
  21.         // 创建一个MediaPlayer的对象,并将多媒体文件加载.   
  22.         player = MediaPlayer.create(this, R.raw.test);  
  23.         // setLooping(boolean);方法,接受的是boolean值   
  24.         // true 表示循环播放   
  25.         // false 表示不循环播放   
  26.         // 默认值为false,即不循环播放   
  27.         player.setLooping(true);  
  28.         super.onCreate();  
  29.     }  
  30.   
  31.     @Override  
  32.     public void onStart(Intent intent, int startId) {  
  33.         // TODO Auto-generated method stub   
  34.         // MediaPlayer对象的start()方法   
  35.         player.start();  
  36.         Log.v("音乐播放""开始");  
  37.         super.onStart(intent, startId);  
  38.     }  
  39.   
  40.     @Override  
  41.     public void onDestroy() {  
  42.         // TODO Auto-generated method stub   
  43.         // MediaPlayer对象的stop()方法   
  44.         player.stop();  
  45.         Log.v("音乐播放""停止");  
  46.         super.onDestroy();  
  47.     }  
  48.   
  49.     @Override  
  50.     public boolean onUnbind(Intent intent) {  
  51.         // TODO Auto-generated method stub   
  52.         // MediaPlayer对象的stop()方法   
  53.         Log.v("音乐播放""停止#####onUnbind");  
  54.         return super.onUnbind(intent);  
  55.     }  
  56.   
  57.     @Override  
  58.     public IBinder onBind(Intent intent) {  
  59.         // TODO Auto-generated method stub   
  60.         // MediaPlayer对象的start()方法   
  61.         player.start();  
  62.         Log.v("音乐播放""开始####onBind");  
  63.         return null;  
  64.     }  
  65.   
  66. }  
package com.yongchun.intent.ui;

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

/**
 * 作者:肥鱼 QQ群:104780991 Email:zhaoyongchun2011@gmail.com
 * 关于:一条致力于Android开源事业的鱼,还是肥的.吃得多赚的少还不会暖床,求包养.
 */
public class PlayRadioService extends Service {

	private MediaPlayer player;

	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		Log.v("PlayRadioSevice", "Service onCreat()执行成功");
		// 创建一个MediaPlayer的对象,并将多媒体文件加载.
		player = MediaPlayer.create(this, R.raw.test);
		// setLooping(boolean);方法,接受的是boolean值
		// true 表示循环播放
		// false 表示不循环播放
		// 默认值为false,即不循环播放
		player.setLooping(true);
		super.onCreate();
	}

	@Override
	public void onStart(Intent intent, int startId) {
		// TODO Auto-generated method stub
		// MediaPlayer对象的start()方法
		player.start();
		Log.v("音乐播放", "开始");
		super.onStart(intent, startId);
	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		// MediaPlayer对象的stop()方法
		player.stop();
		Log.v("音乐播放", "停止");
		super.onDestroy();
	}

	@Override
	public boolean onUnbind(Intent intent) {
		// TODO Auto-generated method stub
		// MediaPlayer对象的stop()方法
		Log.v("音乐播放", "停止#####onUnbind");
		return super.onUnbind(intent);
	}

	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		// MediaPlayer对象的start()方法
		player.start();
		Log.v("音乐播放", "开始####onBind");
		return null;
	}

}

对应的清单文件如下所示,需要将定义的Service在清单文件中进行注册。


  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     package="com.yongchun.intent.ui"  
  4.     android:versionCode="1"  
  5.     android:versionName="1.0" >  
  6.   
  7.     <uses-sdk android:minSdkVersion="8" />  
  8.   
  9.     <application  
  10.         android:icon="@drawable/ic_launcher"  
  11.         android:label="@string/app_name" >  
  12.         <activity  
  13.             android:name=".MainActivity"  
  14.             android:label="@string/app_name" >  
  15.             <intent-filter>  
  16.                 <action android:name="android.intent.action.MAIN" />  
  17.   
  18.                 <category android:name="android.intent.category.LAUNCHER" />  
  19.             </intent-filter>  
  20.         </activity>  
  21.   
  22.         <service android:name=".PlayRadioService" >  
  23.         </service>  
  24.     </application>  
  25.   
  26. </manifest>  
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.yongchun.intent.ui"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="8" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".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=".PlayRadioService" >
        </service>
    </application>

</manifest>

点击下载示例代码


插播广告: QQ群:   104780991   欢迎致力于Android开源事业的朋友.



版权声明:本文为博主原创文章,未经博主允许不得转载。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值