Services trong Android


Một Service là một thành phần được chạy bên trong nền để xử lý các công việc trong thời gian dài. Một ứng dụng nghe nhạc có thể phát nhạc, trong khi đó người dùng đang ở giao diện của ứng dụng khác. Hoặc ứng dụng download có thể tải dữ liệu trên mạng về máy mà không ngăn chặn người dùng tương tác với các ứng dụng khác. Một Service gồm hai trạng thái cơ bản:

  • Started: Một service được gọi là started khi một thành phần của ứng dụng, chẳng hạn như là activity, start nó bằng cách gọi phương thức startService(). Mỗi lần được started, service chạy bên dưới vô thời hạn, thậm chí ngay cả khi thành phần đã started nó bị hủy.
  • Bound: Một service được gọi là bound khi một thành phần ứng dụng liên kết với nó bằng cách gọi phương thức bindService(). Một dịch vụ ràng buộc cung cấp một giao diện client-server cho phép các thành phần tương tác với service, gửi yêu cầu, nhận kết quả, thậm chí tương tự trong việc giao tiếp với interprocess (IPC).

Mỗi service có tập các phương thức và bạn có thể implement để giám sát việc thay đổi các trạng thái của service, và thậm chí bạn có thể thực hiện các công việc ở mỗi trạng thái thích hợp.

Trong sơ đồ sau phía bên trái mô tả vòng đời của service khi được tạo với startService(), và phía bên phải mô tả vòng đời của service khi được tạo với bindService().

Để tạo một service bạn có thể tạo một class kế thừa class Service. Class Service có nhiều phương thức callback, bạn không cần phải implement hết các phương thức này, tuy nhiên việc hiểu rõ và áp dụng chúng trong code là rất quan trọng trong việc đáp ứng yêu cầu của người dùng.

  • onStartCommand(): Hệ thống gọi phương thức này khi có một thành phần khác, chẳng hạn như activity, yêu cầu service đã được started, bởi gọi phương thúc startService(). Nếu bạn implement phương thức này thì bạn phải có trách nhiệm stop service khi công việc của nó đã hoàn thành, bằng cách gọi phương thức stopSelf() hoặc stopService().
  • onBind(): Hệ thống gọi phương thức này khi có một thành phần khác một liên kết với service bằng cách gọi phương thức bindService(). Nếu bạn implement phương thức này, thì bạn phải cung cấp một giao diện để client sử dụng giao tiếp với service, bằng cách trả về đối tượng IBinder. Bạn phải luôn implement phương thức này, tuy nhiên nếu bạn không muốn các liên kết, thì có thể trả vể null.
  • onUnbind(): Hệ thống gọi phương thức này khi tất cả các client đã bị ngắt kết nối từ một giao diện đặt biệt được tạo bởi các service.
  • onRebind(): Hệ thống gọi phương thức này khi có một client mới được kết nối với service, mà trước đó đã có thông báo rằng tất cả đã bị ngắt kết nối bởi onUnbind().
  • onCreate(): Hệ thống gọi phương thức này khi service được tạo lần đầu tiên bởi gọi phương thức onStartCommand() hoặc onBind().
  • onDestroy(): Hệ thống gọi phương thức này khi service đã không còn được sử dụng trong thời gian dài. Bạn nên gọi phương phức này để giải phóng các tài nguyên hệ thống.

Ví dụ: Ví dụ này mang đến cho bạn các bước đơn giản để tạo một service trong Android. Bạn tiến hành theo các bước sau:

Tạo project với tên: ServiceExample

File: res/values/strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">ServiceExample</string>
    <string name="action_settings">Settings</string>
    <string name="hello_world">Hello world!</string>
    <string name="start_service">Start Service</string>
    <string name="stop_service">Stop Service</string>

</resources>

File: res/layout/activity_main.xml

<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/btnStartService"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/start_service"
        android:onClick="startService" />

    <Button android:id="@+id/btnStopService"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/stop_service"
        android:onClick="stopService" />

</LinearLayout>

File: src/com.example.serviceexample/MyService.java

package com.example.serviceexample;

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) {
		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();
	}

}

File: AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.serviceexample"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="18" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.serviceexample.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="com.example.serviceexample.MyService"></service>

    </application>

</manifest>

File: src/com.example.serviceexample/MainActivity.java

package com.example.serviceexample;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;

public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	public void startService(View view){
		startService(new Intent(getBaseContext(), MyService.class));
	}

	public void stopService(View view){
		stopService(new Intent(getBaseContext(), MyService.class));
	}
}

Kết quả:

Khi click vào button: Start Service

Khi click vào button: Stop Service

DOWNLOAD: Source code

 

 

 

Dựa trên: tutorialspoint

Leave a comment