在這邊紀錄一下新增一個背景服務所需要的步驟,方便以後快速新增。
1.新增一個Service Class (以BtService為例)
public class BtService extends Service {
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public void onCreate() {
super.onCreate();
//剛進入時執行
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
//第二執行,主要運作區
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
super.onDestroy();
//關閉服務時執行
}
}
2021/09/14 更新Kotlin版:
import android.app.Service
import android.content.Intent
import android.os.IBinder
class WidgetUpdateService : Service() {
override fun onBind(p0: Intent?): IBinder? {
TODO("Not yet implemented")
}
override fun onCreate() {
super.onCreate()
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
return super.onStartCommand(intent, flags, startId)
}
override fun onDestroy() {
super.onDestroy()
}
}
2.在Manifest.xml增加此服務
<service android:name=".Services.BTControlServer.BtService" android:exported="false" />
3.啟動服務
Intent btIntent = new Intent(MainActivity.this, BtService.class); startService(btIntent);
4.關閉服務
Intent btIntent = new Intent(this, BtService.class); stopService(btIntent);
延伸閱讀:
-END-
發佈留言