<?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:id="@+id/bt_startService"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="启动Service"
/>
<Button
android:id="@+id/bt_stopService"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="关闭Service"
/>
<Button
android:id="@+id/bt_bindService"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="绑定Service"
/>
<Button
android:id="@+id/bt_unbindService"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="松绑Service"
/>
<Button
android:id="@+id/bt_closeApplication"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="退出程序"
/>
</LinearLayout>
strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="hello">Hello World, ServiceTest!</string>
<string name="app_name">ServiceTest01</string>
<string name="Service_started">Service_started</string>
</resources>
AndroidManifest.xml<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.hyz"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".ServiceTest"
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=".MyService" android:exported="true">
<intent-filter>
<action android:name="com.hyz.PlayService.PLAY_MUSIC" />
<category android:name="android.intent.category.default" />
</intent-filter>
</service>
</application>
</manifest>
package com.hyz; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.Service; import android.content.Intent; import android.media.MediaPlayer; import android.os.Binder; import android.os.IBinder; import android.util.Log; /* * 启动service有两种方式,一种startService(intent); * 另一种 bindService(intent, serviceConnection, BIND_AUTO_CREATE); * 这两种的区别:第一种你在(手机menu-->设置-->应用程序—>正在运行的服务) * 里能看到你的服务 。第二种你在上面的地方看不到, * 原因是第二种绑定服务后它将与其绑定的Activity同生同灭。 */ public class MyService extends Service { private MediaPlayer player; private final String service = "Service"; public static String serviceState = "";//要定义成静态的,否则调用下面的函数并不能改变其“”值 private NotificationManager _nm; private MyBinder mBinder = new MyBinder(); //用于Activity绑定时回调 @Override public IBinder onBind(Intent arg0) { //绑定Service,绑定后不能再绑定;只有松绑后,才可以再绑定。 // TODO Auto-generated method stub //被绑定的Service只有onUnbind(), Log.e(service, "MyService-->onBind()"); serviceState = "onBind"; return mBinder; } @Override public boolean onUnbind(Intent intent) { //松绑Service,会触发onDestroy() // TODO Auto-generated method stub //还有点要注意,只有绑定了Service,才能松绑, Log.e(service, "MyService-->onUnbind()"); //否则会报错。 serviceState = "onUnbind"; return super.onUnbind(intent); } @Override public void onCreate() { //创建Service // TODO Auto-generated method stub super.onCreate(); Log.e(service, "MyService-->onCreate()"); serviceState = "onCreate"; _nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE); showNotification(); } @Override public void onDestroy() { //销毁Service super.onDestroy(); Log.e(service, "MyService-->onDestroy()"); if(serviceState.equals("onStart")) player.stop(); serviceState = "onDestroy"; } @Override public void onStart(Intent intent, int startId) { //启动Service,可以启动多次 super.onStart(intent, startId); Log.e(service, "MyService-->onStart()"); serviceState = "onStart"; player = MediaPlayer.create(this, R.raw.gequ); player.start(); } /** * 用于Activity绑定时回调,调用ServiceConnection.onServiceConnected方法 * */ public class MyBinder extends Binder { MyService getService() { Log.e(service, "MyService-->MyBinder-->getService()"); return MyService.this; } } private void showNotification() { Notification notification = new Notification(R.drawable.icon,"service started",System.currentTimeMillis()); PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this,ServiceTest.class), 0); notification.setLatestEventInfo(this, "test service","service started" , contentIntent); _nm.notify(R.string.Service_started,notification); } }
package com.hyz; 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.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.Toast; public class ServiceTest extends Activity{ private Button bt_startServiect; private Button bt_stopServiect; private Button bt_bindServiect; private Button bt_unbindServiect; private Button bt_closeApp; //绑定Service需要用到的对象,是Activity与Service间连接的中介 private ServiceConnection serviceConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName name, IBinder service) { Toast.makeText(ServiceTest.this, "The Program is Binding!", Toast.LENGTH_SHORT).show(); Log.e("Service", "ServiceTest-->onServiceConnected(serviceConnection)"); } @Override public void onServiceDisconnected(ComponentName name) { Log.e("Service", "ServiceTest-->onServiceDisconnected(serviceConnection)"); } }; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Log.e("Service", "ServiceTest-->onCreate()"); setContentView(R.layout.main); InitView(); } @Override protected void onDestroy() { super.onDestroy(); Log.e("Service", "ServiceTest-->onDestroy()"); Log.e("Activity", "onDestroy"); } private void InitView() { Log.e("Service", "ServiceTest-->InitView()"); bt_startServiect = (Button) findViewById(R.id.bt_startService); bt_stopServiect = (Button) findViewById(R.id.bt_stopService); bt_bindServiect = (Button) findViewById(R.id.bt_bindService); bt_unbindServiect = (Button) findViewById(R.id.bt_unbindService); bt_closeApp = (Button) findViewById(R.id.bt_closeApplication); bt_startServiect.setOnClickListener(new ClickEvent()); bt_stopServiect.setOnClickListener(new ClickEvent()); bt_bindServiect.setOnClickListener(new ClickEvent()); bt_unbindServiect.setOnClickListener(new ClickEvent()); bt_closeApp.setOnClickListener(new ClickEvent()); } private class ClickEvent implements OnClickListener { @Override public void onClick(View v) { Intent intent = new Intent(ServiceTest.this, MyService.class); switch(v.getId()) { case R.id.bt_startService: //启动Service:OnCreate()->onStart() Log.e("Service", "ServiceTest-->ClickEvent-->onClick(bt_startService)"); startService(new Intent("com.hyz.PlayService.PLAY_MUSIC")); Log.e("Service", MyService.serviceState); break; case R.id.bt_stopService: //关闭Service:onDestroy() Log.e("Service", "ServiceTest-->ClickEvent-->onClick(bt_stopService)"); ServiceTest.this.stopService(intent); Log.e("Service", MyService.serviceState); break; case R.id.bt_bindService: //绑定Service:OnCreate()->onBind() Log.e("Service", "ServiceTest-->ClickEvent-->onClick(bt_bindService)"); ServiceTest.this.bindService(intent, serviceConnection, BIND_AUTO_CREATE); Log.e("Service", MyService.serviceState); break; case R.id.bt_unbindService: //松绑Service:onUnbind()->onDestroy() Log.e("Service", "ServiceTest-->ClickEvent-->onClick(bt_unbindService)"); if("onBind".equals(MyService.serviceState)) { //只有绑定了,才能松绑,否则报错 ServiceTest.this.unbindService(serviceConnection); } Log.e("Service", MyService.serviceState); break; case R.id.bt_closeApplication://关闭程序 Log.e("Service", "ServiceTest-->ClickEvent-->onClick(bt_closeApplication)"); ServiceTest.this.finish(); break; default: break; } } } }
1、启动Service: startService(intent);
OnCreate()-->onStart()
2、关闭Service: stopService(intent);
OnDestroy()
3、绑定Service: bindService(intent, serviceConnection, BIND_AUTO_CREATE);
OnCreate()-->OnBind()-->onServiceConnected(serviceConnection)
4、松绑Service: unbindService(serviceConnection);
onUnbind()-->onDestroy()
在Android中Activity是前台进程,而Service则是后台进程。Activity是有界面的,Service是没有界面。那何时使用Service?最经典的例子是播放音乐时,你想退出音乐播放,而不想音乐因为界面的退出而停止播放。那么使用Service就很好的解决了这个问题。
Service的生命周期比较简单,具体状态如下:
主要有两种形式,根据驱动方式的不同而划分:
1、不绑定启动:
onCreate() --> onStart --> onDestroy();
2、绑定启动:
onCreate() --> onBind --> onUnbind --> onDestroy();
当然,上面两种方式可以混合着用,例如:onCreate() --> onStart --> sonBind --> onUnbind --> sonDestroy()。有几点要注意的是:
1、一个Service可以启动多次,但绑定时,仅能绑定一次。
2、调用OnBind绑定程序时,只有两种情况Service才会销毁:第一种是绑定它的Activity对象结束;第二种是调用OnUnbind方法松绑。
3、对于调用OnStart启动的Service,它不会随着调用它的Activity结束而结束,只有等它自动结束或调用Kiill方法才行。这也是实现即使界面退出,音乐仍然继续播放的关键。虽然Service是在Activity中调用,但Activity只起到启动它的作用,而Service后续的操作,不会受到Activity关闭的影响。
4只有OnBind绑定程序后,才能调用OnUnbind方法,否则会报错。
启动service有两种方式,一种startService(intent);另一种 bindService(intent, serviceConnection, BIND_AUTO_CREATE);这两种的区别:第一种你在(手机menu-->设置-->应用程序—>正在运行的服务)里能看到你的服务。第二种你在上面的地方看不到,原因是第二种绑定服务后它将与其绑定的Activity同生同灭。