Service概念及用途:
Android中的服務,它與Activity不同,它是不能與用戶交互的,不能自己啟動的,運行在后臺的程序,如果我們退出應用時,Service進程并沒有結束,它仍然在后臺運行,那我們什么時候會用到Service呢?比如我們播放音樂的時候,有可能想邊聽音樂邊干些其他事情,當我們退出播放音樂的應用,如果不用Service,我們就聽不到歌了,所以這時候就得用到Service了,又比如當我們一個應用的數據是通過網絡獲取的,不同時間(一段時間)的數據是不同的這時候我們可以用Service在后臺定時更新,而不用每打開應用的時候在去獲取。
Service生命周期 :
Android Service的生命周期并不像Activity那么復雜,它只繼承了onCreate(),onStart(),onDestroy()三個方法,當我們第一次啟動Service時,先后調用了onCreate(),onStart()這兩個方法,當停止Service時,則執行onDestroy()方法,這里需要注意的是,如果Service已經啟動了,當我們再次啟動Service時,不會在執行onCreate()方法,而是直接執行onStart()方法。
Service與Activity通信:
Service后端的數據最終還是要呈現在前端Activity之上的,因為啟動Service時,系統會重新開啟一個新的進程,這就涉及到不同進程間通信的問題了(AIDL),當我們想獲取啟動的Service實例時,我們可以用到bindService和unBindService方法,它們分別執行了Service中IBinder()和onUnbind()方法。
1、添加一個類,在MainActivity所在包之下
<Button
android:id="@+id/startservice"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="startService" />
<Button
android:id="@+id/stopservice"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="stopService" />
<Button
android:id="@+id/bindservice"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="bindService" />
<Button
android:id="@+id/unbindservice"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="unbindService" />
startServiceButton = (Button) findViewById(R.id.startservice);
stopServiceButton = (Button) findViewById(R.id.stopservice);
bindServiceButton = (Button) findViewById(R.id.bindservice);
unbindServiceButton = (Button) findViewById(R.id.unbindservice);startServiceButton.setOnClickListener(this);
stopServiceButton.setOnClickListener(this);
bindServiceButton.setOnClickListener(this);
unbindServiceButton.setOnClickListener(this);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setupViews();
}
@Override
public void onClick(View v) {
if (v == startServiceButton) {
Intent i = new Intent(MainActivity.this, LService.class);
mContext.startService(i);
} else if (v == stopServiceButton) {
Intent i = new Intent(MainActivity.this, LService.class);
mContext.stopService(i);
} else if (v == bindServiceButton) {
Intent i = new Intent(MainActivity.this, LService.class);
mContext.bindService(i, mServiceConnection, BIND_AUTO_CREATE);
} else {
mContext.unbindService(mServiceConnection);
}
}
}
<service
android:name=".LService"
android:exported="true" >
</service>
5、運行程序
程序界面
點擊startService此時調用程序設置里面可以看到Running Service有一個LService
點擊stopService
點擊bindService此時Service已經被關閉
點擊unbindService
先點擊startService,再依次點擊bindService和unbindService
新聞熱點
疑難解答
圖片精選