[英]React Native and Android Background Services
我正在使用Headless.js與React Native一起運行后台服務。 我們在使用方面遇到了很多問題。 使用React Native運行Android后台服務有哪些選擇?
添加文件名BackgroundAudio.java
import android.content.Intent;
import android.os.Bundle;
import com.facebook.react.HeadlessJsTaskService;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.jstasks.HeadlessJsTaskConfig;
public class BackgroundAudio extends HeadlessJsTaskService {
@Override
protected @Nullable HeadlessJsTaskConfig getTaskConfig(Intent intent) {
Bundle extras = intent.getExtras();
if (extras != null) {
return new HeadlessJsTaskConfig(
"BackgroundAudio",
Arguments.fromBundle(extras),
5000);
}
return null;
}
}
編輯AndroidManifest.xml
<service android:name=".BackgroundAudio" android:enabled="true" android:label="BackgroundAudio" />
然后在我的index.android.js中:
import BackgroundAudio from './src/BackgroundAudio'
AppRegistry.registerHeadlessTask('BackgroundAudio', () => BackgroundAudio)
最后,index.android.js中引用的BackgroundAudio.js文件讀取如下:
export async function BackgroundAudio (taskData) {
alert('BACKGROUND AUDIO')
}
自從您提出這個問題后,已經創建了幾個軟件包,這些軟件包可能會有所幫助,具體取決於您的確切用例。
具體來說,您可以使用react native queue with react native background任務來輕松安排后台任務定期執行(大約每15分鍾,您的計划任務將運行最多30秒 - 使用隊列來處理任務超時管理)已關閉(這適用於iOS和Android的跨平台)。 但是,如果您打算在后台持續運行服務,我不確定在RN世界中是否可行(就我的帖子而言)。
我的猜測是你必須自己寫。 不幸的是Headless JS暫停任務完成,所以我不確定它是否合適。
只要不觸及UI,您就可以在任務中執行任何操作:網絡請求,計時器等。 一旦您的任務完成(即承諾得到解決),React Native將進入“暫停”模式(除非有其他任務在運行,或者有一個前台應用程序)。
https://facebook.github.io/react-native/docs/headless-js-android.html
更新:如果應用失去焦點,可以保持流程運行。 我將不得不尋找測試應用程序源代碼,以提供一個示例。
順便說一句,我最終在Android中寫了一個后台服務,開始啟動。 React Native不允許這種類型的服務,RN也不打算創建完全無頭的應用程序。 AppRegistry:
AppRegistry.registerHeadlessTask('SomeTaskName', () => require('SomeTaskName'));
SomeTaskName.js:
module.exports = async (taskData) => {
// do stuff
};
Java API:
public class MyTaskService extends HeadlessJsTaskService {
@Override
protected @Nullable HeadlessJsTaskConfig getTaskConfig(Intent intent) {
Bundle extras = intent.getExtras();
if (extras != null) {
return new HeadlessJsTaskConfig(
"SomeTaskName",
Arguments.fromBundle(extras),
5000, // timeout for the task
false // optional: defines whether or not the task is allowed in foreground. Default is false
);
}
return null;
}
}
AndroidManifest.xml中
<service android:name="com.example.MyTaskService" />
例:
Intent service = new Intent(getApplicationContext(), MyTaskService.class);
Bundle bundle = new Bundle();
bundle.putString("foo", "bar");
service.putExtras(bundle);
getApplicationContext().startService(service);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.