1. Định nghĩa về Service .
Service là một một thành phần chạy trên nền tảng Android mà không nhất thiết phải tương tác với người dùng . Nó có thể hoạt động ngay cả khi ứng dụng đã bị kết thúc . Nó gồm 2 state chính :
Start : một service được bắt đầu khi một thành phần của ứng dụng , chả hạn như activity gọi tới method startService() . Khi bắt đầu service có thể chạy ở chế độ background vô thời hạn. Ngay cả khi appliction đó destroy.
Bound : Một service bị ràng buộc với các thành phần của activity khi nó gọi tới bindService() . Nó cung cấp 1 interface client - server cho phép các thành phần tương tác với service , send request , get response ...
2. Vòng đời của service
Dưới đây là vòng đời của service
Cụ thể như sau :
onStartCommand()
|
Hệ thống sẽ gọi tới method này khi một thành phần khác , ví dụ như
activity . Request sẽ được started , khi gọi tới startService(). Nếu bạn cài method
sau , nó sẽ trả về responsity khi stop
service của quá trình làm việc là done , bằng cách gọi tới các method stopSelf()
hoặc stopService()
|
onBind()
|
Hệ thống sẽ gọi tới method này khi các thành phần khác muốn lien kết
(bind) service bởi cách gọi method bindService() . Nếu bạn implement method
này , bạn phải cung cấp một interface client
dung để giao tiếp với service ,
bởi việc trả về đối tượng IBinder . Bạn luôn phải implement method này . Tuy
nhiên nếu bạn không muốn cho phép binding , thì nó sẽ return về null
|
onUnbind()
|
Hệ thống sẽ gọi tới method khi
tất cả client muốn disconnect từ một interface cụ thể đã được pushlish bởi
service
|
onRebind()
|
Hệ thống sẽ gọi tới method này
khi new client đã connect tới service ,sau đó nó đã disconnect trong
onUnbind(Intent)
|
onCreate()
|
Hệ thống gọi tới method này khi service đã được tạo lần đầu
onStartCommand() hoặc onBind() . Lời gọi yêu cầu một khoảng thời gian đã được
setup
|
onDestroy()
|
Hệ thống gọi tới method này
khi service không được sử dụng lâu hoặc bị destroy . Service của bạn
nên được clean đi để giải phóng các thread , registered linstener , receivers…
|
AndroidMenifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="nosoft.com.demoservice"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="19" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
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" />
</application>
</manifest>
MainActivity.java
package nosoft.com.demoservice;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// getMenuInflater().inflate(R.menu.activity_main, menu);
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
// Method to start the service
public void startService(View view) {
startService(new Intent(getBaseContext(), MyService.class));
}
// Method to stop the service
public void stopService(View view) {
stopService(new Intent(getBaseContext(), MyService.class));
}
}
MyService.java
package nosoft.com.demoservice;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;
public class MyService extends Service {
@Override
public IBinder onBind(Intent arg0) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// Let it continue running until it is stopped.
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
}
}
Layout
activity_main.xml
<RelativeLayout 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:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Example services"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:textSize="30dp" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Android tutorial Nosoft"
android:textColor="#ff87ff09"
android:textSize="30dp"
android:layout_above="@+id/imageButton"
android:layout_centerHorizontal="true"
android:layout_marginBottom="40dp" />
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageButton"
android:src="@drawable/abc"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/button2"
android:text="Start Services"
android:onClick="startService"
android:layout_below="@+id/imageButton"
android:layout_centerHorizontal="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Stop Services"
android:id="@+id/button"
android:onClick="stopService"
android:layout_below="@+id/button2"
android:layout_alignLeft="@+id/button2"
android:layout_alignStart="@+id/button2"
android:layout_alignRight="@+id/button2"
android:layout_alignEnd="@+id/button2" />
</RelativeLayout>
Các bạn có thể download full code tại đây để tham khảo : here
Các bạn tự code và chạy để cảm nhận sự thay đổi của app ở Log Cat nhé .