Android Service详解(二)第一个Service
????Service中有四個(gè)重要函數(shù): ?
????public?IBinder?onBind(Intent?arg0);????//必須實(shí)現(xiàn),返回接口給Servicepublic?void?onCreate();????????????????//Service創(chuàng)建時(shí)調(diào)用public?void?onStart(Intent?intent,int?startId);//通過startService()會(huì)調(diào)用public?void?onDestroy();????????????????//銷毀時(shí)StopService()調(diào)用?
通過StartActivity()函數(shù)啟動(dòng)Service,當(dāng)?shù)谝淮握{(diào)用時(shí)會(huì)分別調(diào)用onCreate()和onStart在();
之后只會(huì)調(diào)用onStart();
通過函數(shù)StopService()結(jié)束Service,會(huì)調(diào)用onDestroy();
調(diào)用BindService():當(dāng)Service未創(chuàng)建時(shí)調(diào)用onCreate()和onBind();當(dāng)創(chuàng)建了只調(diào)用onBind();
使用函數(shù)bindService()和函數(shù)unbindService()可以綁定和解除綁定
對已經(jīng)綁定的Service調(diào)用bindService()無效,即多次調(diào)用bindService()和調(diào)用一次bindService()一樣。 unbindService()只能使用一次,即對于一個(gè)綁定的Service,只能調(diào)用一次unbindService(),多次調(diào)用會(huì)產(chǎn)生錯(cuò)誤
該函數(shù)原型為:
ServiceConnection是一個(gè)服務(wù)連接類,必須實(shí)現(xiàn)以下兩個(gè)函數(shù):
public?void?onServiceConnected(ComponentName?arg0,?IBinder?arg1)//連接成功時(shí)調(diào)用 public?void?onServiceDisconnected(ComponentName?arg0)????????//連接失敗時(shí)調(diào)用????示例如下:
????
????
Service實(shí)例:
????MainActivity.java:
NewService.java:
public?class?NewService?extends?Service?{@Overridepublic?IBinder?onBind(Intent?arg0)?{//?TODO?Auto-generated?method?stubToast.makeText(NewService.this,?"onBind",?Toast.LENGTH_LONG).show();Log.i("SERVICE","onbind");return?null;}public?void?onCreate()?{super.onCreate();Log.i("SERVICE","oncreat");Toast.makeText(NewService.this,?"onCreat",?Toast.LENGTH_LONG).show();}public?void?onStart(Intent?intent,int?startId)?{Log.i("SERVICE","onstart");Toast.makeText(NewService.this,?"onStart",?Toast.LENGTH_LONG).show();}public?void?onDestroy()?{Log.i("SERVICE","ondestory");Toast.makeText(NewService.this,?"onDestory",?Toast.LENGTH_LONG).show();} }Activity.xml
<?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"?><Button?android:id="@+id/btn1"?android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="start"/><Button?android:id="@+id/btn3"?android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="stop"/><Button?android:id="@+id/btn4"?android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="bind"/><Button?android:id="@+id/btn5"?android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="unbind"/>???? </LinearLayout>AndroidManifest.xml增加:
轉(zhuǎn)載于:https://blog.51cto.com/aslonely/1616665
《新程序員》:云原生和全面數(shù)字化實(shí)踐50位技術(shù)專家共同創(chuàng)作,文字、視頻、音頻交互閱讀總結(jié)
以上是生活随笔為你收集整理的Android Service详解(二)第一个Service的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Arduino vs Raspberry
- 下一篇: Android内核开发:系统编译输出的镜