標籤:service bind android 開發
安卓中服務的開啟方式
一:採用start的方式開啟服務
調用函數:startService(Intent)->onCreate()->onStart()/onStartCommand()->onDestroy()
特點:服務被開啟後不會重複開啟,只會調用onStart(),服務只會被停止一次。
二:採用bind的方式開發服務
調用函數:bindService(Intent…)->onCreate()->onBind()->onUnBind()->onDestroy();
特點:綁定不會調用onStart()[過時了]和onStartCommand()方法。
兩種服務的區別:
start方式開發服務,一旦服務開啟跟調用者就沒有任何關係了,比如我們的服務是在Activity中調用開啟的,當Activity關閉的時候,服務不會關閉。
bind方式開啟服務,調用者沒了,服務也會關閉,可以理解為同生共死。
對於start開啟服務的方式比較簡單,重點講解bind的方式!
例子:
1.布局裡面設定三個按鈕
2.為按鈕設定監聽事件,有好幾種方式。
3.處理事件。當點擊綁定的時候:
/*綁定的建立方式 */ Intent intent = new Intent(this, MyService.class); bindService(intent, conn, BIND_AUTO_CREATE);
conn是自己實現的功能類,繼承自ServiceConnection。
完整代碼如下:
public class MainActivity extends ActionBarActivity { private MyConn conn; private Call c; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);//Call類似中間人的功能。 } public void bind(View v){ conn = new MyConn(); Intent intent = new Intent(this, MyService.class); bindService(intent, conn, BIND_AUTO_CREATE); } public void unbind(View v){ unbindService(conn); c = null; } /* * 調用服務裡的方法 */ public void call(View v){ c.callMethodInService(); } private class MyConn implements ServiceConnection{ @Override public void onServiceConnected(ComponentName name, IBinder service) { System.out.println("調用服務裡面的方法"); c = (Call) service; } @Override public void onServiceDisconnected(ComponentName name) { } }}
service代碼如下:
public class MyService extends Service { @Override public IBinder onBind(Intent intent) { System.out.println("服務被成功綁定了"); return new Call(); } @Override public void onCreate() { System.out.println("onCreate"); super.onCreate(); } @Override public int onStartCommand(Intent intent, int flags, int startId) { System.out.println("onstartCommand"); return super.onStartCommand(intent, flags, startId); } @Override public void onDestroy() { System.out.println("ondestroy"); super.onDestroy(); } public void methodInService(){ Toast.makeText(this, "methodInService", 0).show(); } public class Call extends Binder{ public void callMethodInService(){ methodInService(); } }}
布局檔案:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context="com.example.servicelife.MainActivity" > <Button android:onClick="bind" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="start"/> <Button android:onClick="unbind" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="end"/> <Button android:onClick="call" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="調用服務裡的方法"/></LinearLayout>
安卓服務(Service)的兩種開啟方式以及服務的生命週期