Service是Andorid系统提供的四大组件之一,它的地位和Activity是并列的,只是使用的频率没有Activity高。Service就是运行于后台的一种服务程序,一般很少和用户交互,因此没有可视化界面。
定义一个Service类只要继承Service类即可,实现其生命周期中的方法就可以了,另外,一个定义好的Service组件必须要在AndoridManifest.xml文件中注册才能够使用。
Service有自己的生命周期,可以调用startService()启动一个Service或者使用bindService()来绑定一个service,还可以通过RPC(远程进程调用)机制来实现不同进程间Service的调用。
Service中定义了一系列和自身生命周期相关的方法:
onBind(Intent intent):是必须实现的一个方法,返回一个绑定的接口给Service。
onCreate():当Service第一次被创建时,由系统调用。
onStart(Intent intent,int startId):当通过startService()方法启动Service时,该方法被调用。
onDestroy():当Service不再使用,系统调用该方法。
实例如下:
MyService.java
- /*
- *@authorhualang
- */
- packageorg.hualang.service;
-
- importandroid.app.Service;
- importandroid.content.Intent;
- importandroid.os.IBinder;
- importandroid.util.Log;
- importandroid.widget.Toast;
-
- publicclassMyServiceextendsService{
-
- @Override
- publicIBinderonBind(Intentintent){
- //TODOAuto-generatedmethodstub
- Log.i("SERVICE","onBind.................");
- Toast.makeText(MyService.this,"onBind.................",Toast.LENGTH_LONG).show();
- returnnull;
- }
-
- publicvoidonCreate()
- {
- Log.i("SERVICE","onCreate................");
- Toast.makeText(MyService.this,"onCreate................",Toast.LENGTH_LONG).show();
- }
- publicvoidonStart(Intentintent,intstartId)
- {
- Log.i("SERVICE","onStart.................");
- Toast.makeText(MyService.this,"onStart.................",Toast.LENGTH_LONG).show();
- }
- publicvoidonDestroy()
- {
- Log.i("SERVICE","onDestroy.................");
- Toast.makeText(MyService.this,"onDestroy.................",Toast.LENGTH_LONG).show();
- }
- }
/* * @author hualang */package org.hualang.service;import android.app.Service;import android.content.Intent;import android.os.IBinder;import android.util.Log;import android.widget.Toast;public class MyService extends Service { @Override public IBinder onBind(Intent intent) { // TODO Auto-generated method stub Log.i("SERVICE", "onBind................."); Toast.makeText(MyService.this, "onBind.................", Toast.LENGTH_LONG).show(); return null; } public void onCreate() { Log.i("SERVICE", "onCreate................"); Toast.makeText(MyService.this, "onCreate................", Toast.LENGTH_LONG).show(); } public void onStart(Intent intent,int startId) { Log.i("SERVICE", "onStart................."); Toast.makeText(MyService.this, "onStart.................", Toast.LENGTH_LONG).show(); } public void onDestroy() { Log.i("SERVICE", "onDestroy................."); Toast.makeText(MyService.this, "onDestroy.................", Toast.LENGTH_LONG).show(); }}
ServiceTest.java
- /*
- *@authorhualang
- */
- packageorg.hualang.service;
-
- importandroid.app.Activity;
- importandroid.app.Service;
- importandroid.content.ComponentName;
- importandroid.content.Intent;
- importandroid.content.ServiceConnection;
- importandroid.os.Bundle;
- importandroid.os.IBinder;
- importandroid.util.Log;
- importandroid.view.View;
- importandroid.view.View.OnClickListener;
- importandroid.widget.Button;
- importandroid.widget.Toast;
-
- publicclassServiceTestextendsActivity{
- /**Calledwhentheactivityisfirstcreated.*/
- privateButtonstartService,stopService,bindService,unbindService;
- @Override
- publicvoidonCreate(BundlesavedInstanceState){
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- startService=(Button)findViewById(R.id.startButton);
- stopService=(Button)findViewById(R.id.stopButton);
- bindService=(Button)findViewById(R.id.bindButton);
- unbindService=(Button)findViewById(R.id.unbindButton);
- startService.setOnClickListener(startListener);
- stopService.setOnClickListener(stopListener);
- bindService.setOnClickListener(bindListener);
- unbindService.setOnClickListener(unbindListener);
-
- }
- privateOnClickListenerstartListener=newOnClickListener()
- {
-
- @Override
- publicvoidonClick(Viewv){
- //TODOAuto-generatedmethodstub
- Intentintent=newIntent();
- intent.setAction("org.hualang.service.action.MYSERVICE");
- startService(intent);
- }
-
- };
- privateOnClickListenerstopListener=newOnClickListener()
- {
-
- @Override
- publicvoidonClick(Viewv){
- //TODOAuto-generatedmethodstub
- Intentintent=newIntent();
- intent.setAction("org.hualang.service.action.MYSERVICE");
- stopService(intent);
- }
-
- };
- privateServiceConnectionconn=newServiceConnection()
- {
-
- @Override
- publicvoidonServiceConnected(ComponentNamename,IBinderservice){
- //TODOAuto-generatedmethodstub
- Log.i("SERVICE","connectionsuccess");
- Toast.makeText(ServiceTest.this,"connectionsuccess",Toast.LENGTH_LONG).show();
- }
-
- @Override
- publicvoidonServiceDisconnected(ComponentNamename){
- //TODOAuto-generatedmethodstub
- Log.i("SERVICE","connectionsuccess");
- Toast.makeText(ServiceTest.this,"connectionfailure",Toast.LENGTH_LONG).show();
- }
-
- };
- privateOnClickListenerbindListener=newOnClickListener()
- {
-
- @Override
- publicvoidonClick(Viewv){
- //TODOAuto-generatedmethodstub
- Intentintent=newIntent();
- intent.setAction("org.hualang.service.action.MYSERVICE");
- bindService(intent,conn,Service.BIND_AUTO_CREATE);
- }
-
- };
- privateOnClickListenerunbindListener=newOnClickListener()
- {
-
- @Override
- publicvoidonClick(Viewv){
- //TODOAuto-generatedmethodstub
- Intentintent=newIntent();
- intent.setAction("org.hualang.service.action.MYSERVICE");
- unbindService(conn);
- }
-
- };
- }
/* * @author hualang */package org.hualang.service;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 ServiceTest extends Activity { /** Called when the activity is first created. */ private Button startService,stopService,bindService,unbindService; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); startService=(Button)findViewById(R.id.startButton); stopService=(Button)findViewById(R.id.stopButton); bindService=(Button)findViewById(R.id.bindButton); unbindService=(Button)findViewById(R.id.unbindButton); startService.setOnClickListener(startListener); stopService.setOnClickListener(stopListener); bindService.setOnClickListener(bindListener); unbindService.setOnClickListener(unbindListener); } private OnClickListener startListener=new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub Intent intent=new Intent(); intent.setAction("org.hualang.service.action.MYSERVICE"); startService(intent); } }; private OnClickListener stopListener=new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub Intent intent=new Intent(); intent.setAction("org.hualang.service.action.MYSERVICE"); stopService(intent); } }; private ServiceConnection conn=new ServiceConnection() { @Override public void onServiceConnected(ComponentName name, IBinder service) { // TODO Auto-generated method stub Log.i("SERVICE", "connection success"); Toast.makeText(ServiceTest.this, "connection success", Toast.LENGTH_LONG).show(); } @Override public void onServiceDisconnected(ComponentName name) { // TODO Auto-generated method stub Log.i("SERVICE", "connection success"); Toast.makeText(ServiceTest.this, "connection failure", Toast.LENGTH_LONG).show(); } }; private OnClickListener bindListener=new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub Intent intent=new Intent(); intent.setAction("org.hualang.service.action.MYSERVICE"); bindService(intent,conn,Service.BIND_AUTO_CREATE); } }; private OnClickListener unbindListener=new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub Intent intent=new Intent(); intent.setAction("org.hualang.service.action.MYSERVICE"); unbindService(conn); } };}
在AndroidManifest.xml文件中注册Service如下
- <serviceandroid:name="MyService">
- <intent-filter>
- <actionandroid:name="org.hualang.service.action.MYSERVICE"/>
- </intent-filter>
- </service>
<service android:name="MyService"> <intent-filter> <action android:name="org.hualang.service.action.MYSERVICE"/> </intent-filter> </service>
main.xml布局文件
- <?xmlversion="1.0"encoding="utf-8"?>
- <LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
- android:orientation="vertical"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- >
- <Button
- android:text="启动Service"
- android:id="@+id/startButton"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- />
- <Button
- android:text="停止Service"
- android:id="@+id/stopButton"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- />
- <Button
- android:text="绑定Service"
- android:id="@+id/bindButton"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- />
- <Button
- android:text="解除绑定unbindService"
- android:id="@+id/unbindButton"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- />
- </LinearLayout>
<?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:text="启动Service" android:id="@+id/startButton" android:layout_width="fill_parent" android:layout_height="wrap_content" /> <Button android:text="停止Service" android:id="@+id/stopButton" android:layout_width="fill_parent" android:layout_height="wrap_content" /> <Button android:text="绑定Service" android:id="@+id/bindButton" android:layout_width="fill_parent" android:layout_height="wrap_content" /> <Button android:text="解除绑定unbindService" android:id="@+id/unbindButton" android:layout_width="fill_parent" android:layout_height="wrap_content" /></LinearLayout>
不解释,看运行结果就会明白
(1)当点击“启动Servcie”会先弹出"onCreate",然后弹出"onStart"的Toast,在LogCat中会看到先显示
的也是
onCreate
onStart
(2)点击“停止Service”按钮,会弹出onDestroy的Toast
LogCat中也会显示
onDestroy()
(3)点击"绑定Service"按钮,会弹出onCreate和onBind的Toast
LogCat中显示
onCreate
onBind
(4)点击“解除绑定Service”按钮,会弹出onDestroy的Toast,LogCat中也如此
下面是LogCat中显示的信息
分享到:
相关推荐
玩转Android---组件篇---Handler的使用玩转Android---组件篇---Handler的使用玩转Android---组件篇---Handler的使用
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 ...
内容包含:android-support-v4_1.6.0_26_20120316.jar android-support-v4_1.6.0_26_20120623.jar android-support-v4_1.6.0_26_20120730.jar android-support-v4_1.6.0_26_20121109.jar android-support-v4_1.6.0_26...
•Android---UI篇---Tab Layout(选项卡布局) • •Andorid---UI篇---TableLayout(表格布局) • •Android---UI篇---RelativeLayout(相对布局) • •Android---UI篇---GridView(网格布局) • •Android---UI篇-...
android-support-v4-v7-v13-v14-v17(官方最新完整版),官方最新版的,压缩包内包含android-support-v4、android-support-v7-appcompat,android-support-v7-cardview,android-support-v7-gridlayout,android-support-...
Android-Service组件应用-模拟下载
axure 的Android-L组件库,比较全
android-sdk\platforms\android-21
android-26 sdk下载 android-26 sdk下载 android-26 sdk下载 android-26 sdk下载
Android-ffmpeg-android-java.zip,使用HTTPS://GithuB.COM/Wrngs/FFMPEG-Android编译的FFMPEG二进制的Android Java库,安卓系统是谷歌在2008年设计和制造的。操作系统主要写在爪哇,C和C 的核心组件。它是在linux内核...
android-sdk_r24.4.1-windows和android-ndk-r10e-windows-x86_64。文件太大只能传到百度云上
android-sdk-windowsandroid-sdk-windowsandroid-sdk-windowsandroid-sdk-windowsandroid-sdk-windowsandroid-sdk-windowsandroid-sdk-windows
Android---Service Timer之执行周期任务
将android-17.zip解压到 Android\android-sdk\platforms 文件夹下。
android linux交叉编译工具aarch64-linux-android-4.9版本!需要的可以下载!
http://s1.eoeandroid.com/sdk/4.1/android-sdk_r20-windows.zip(推荐) http://s1.eoeandroid.com/sdk/4.1/installer_r20-windows.exe Mac版: http://s1.eoeandroid.com/sdk/4.1/android-sdk_r20-macosx.zip ...
最新版的android-support-v4.jar,1.39M左右,包含常用的类库,最新版的android-support-v4.jar,1.39M左右,包含常用的类库
Android-Service系列之断点续传下载