ภาพรวม
START_STICKY เป็นฟลั็กการคืนค่าของ onStartCommand() ใน Service บอกระบบว่า หาก Service ถูกฆ่าเนื่องจากหน่วยความจำไม่พอ หรือเหตุผลอื่นๆ ให้รีสตาร์ท 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.app.ActivityManager;
import android.content.Context;
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 (isMyServiceRunning(StickyService.class)) {
text.setText("Stopped");
stopService(new Intent(MainActivity.this, StickyService.class));
} else {
text.setText("Started");
startService(new Intent(MainActivity.this, StickyService.class));
}
}
});
}
private boolean isMyServiceRunning(Class<?> serviceClass) {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
}
สร้าง Service ใช้ START_STICKY (src/StickyService.java)
package com.example.andy.myapplication;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
public class StickyService extends Service {
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "Sticky Service started", Toast.LENGTH_LONG).show();
Log.d("Tutorialspoint", "Service is working in background");
// คืนค่า START_STICKY - ระบบจะรีสตาร์ท service หากถูกฆ่า
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Sticky Service destroyed", 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=".StickyService"/>
</application>
</manifest>
การทดสอบ
รันแอป คลิก TextView เพื่อเริ่ม Service ลองปิดแอปหรือล้างหน่วยความจำ Service จะรีสตาร์ทอัตโนมัติ (ตรวจสอบได้จาก Logcat)
ค่าคืนค่าอื่นๆ ของ onStartCommand
- START_STICKY - รีสตาร์ท service หากถูกฆ่า (Intent จะเป็น null)
- START_NOT_STICKY - ไม่รีสตาร์ท หากถูกฆ่า (ค่าเริ่มต้น)
- START_REDELIVER_INTENT - รีสตาร์ทและส่ง Intent เดิมกลับมาใหม่
กรณีใช้งาน START_STICKY
- Service ที่ต้องทำงานตลอดเวลา เช่น Music Player, Location Tracker
- งานที่สำคัญและต้องการความน่าเชื่อถือสูง