ภาพรวม
Background Service ใน Android คือคอมโพเนนต์ที่ทำงานในพื้นหลังโดยไม่มี UI และยังคงทำงานต่อแม้ Activity จะถูกทำลาย บทความนี้สาธิตการสร้าง Background Service แบบพื้นฐาน
ขั้นตอนที่ 1: สร้างโปรเจกต์ใหม่
เปิด Android Studio ไปที่ File → New Project กรอกรายละเอียดที่จำเป็นทั้งหมดเพื่อสร้างโปรเจกต์ใหม่
ขั้นตอนที่ 2: จัดทำ Layout (res/layout/activity_main.xml)
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:app="https://schemas.android.com/apk/res-auto"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Start Service"
android:textSize="25sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
ขั้นตอนที่ 3: เขียนโค้ด MainActivity (src/MainActivity.java)
package com.example.andy.myapplication;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView text = findViewById(R.id.text);
text.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (text.getText().toString().equals("Started")) {
text.setText("Stopped");
stopService(new Intent(MainActivity.this, BackgroundService.class));
} else {
text.setText("Started");
startService(new Intent(MainActivity.this, BackgroundService.class));
}
}
});
}
}
สร้าง Background Service (src/BackgroundService.java)
package com.example.andy.myapplication;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;
public class BackgroundService extends Service {
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "Service started by user", Toast.LENGTH_LONG).show();
// ทำงานในพื้นหลังที่นี่
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service destroyed by user", Toast.LENGTH_LONG).show();
}
}
ขั้นตอนที่ 4: ลงทะเบียนใน AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
package="com.example.andy.myapplication">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".BackgroundService"/>
</application>
</manifest>
การทดสอบ
รันแอป คลิก TextView จะเริ่ม Service (แสดง Toast "Service started") คลิกอีกครั้งจะหยุด Service (แสดง Toast "Service destroyed")
ประเภทของ Service ใน Android
- Started Service - เริ่มด้วย startService() ทำงานจนกว่าจะหยุดด้วย stopService() หรือ stopSelf()
- Bound Service - ผูกกับ Component ผ่าน bindService() มี Interface สำหรับสื่อสาร
- Foreground Service - แสดง Notification ทำงานต่อหน้าผู้ใช้
วงจรชีวิตของ Service
onCreate()- เรียกครั้งแรกเมื่อสร้าง ServiceonStartCommand()- เรียกทุกครั้งที่ startService()onDestroy()- เรียกเมื่อ Service ถูกทำลาย