我在Java中创建了一个本机模块,负责在后台运行服务。
我在ClassA
中有这个方法:
@ReactMethod
public void startService(final Promise promise) {
Intent intent = new Intent(getCurrentActivity(), BackgroundService.class);
intent.putExtra(BackgroundService.FILENAME, "test123.html");
intent.putExtra(BackgroundService.URL,
"http://www.vogella.com/index.html");
Activity currentActivity = getCurrentActivity();
if (currentActivity == null) {
promise.reject("Activity doesnt exist");
} else {
getCurrentActivity().startService(intent);
}
}
以下是BackgroundService
中的代码:
public class BackgroundService extends IntentService {
private int result = Activity.RESULT_CANCELED;
public static final String URL = "urlpath";
public static final String FILENAME = "filename";
public static final String FILEPATH = "filepath";
public static final String RESULT = "result";
public static final String NOTIFICATION = "com.vogella.android.service.receiver";
public BackgroundService() {
super("BackgroundService");
}
public String getName() {
return "BackgroundService";
}
@Override
protected void onHandleIntent(Intent intent) {
//do stuff
ClassA.servicePromise.resolve("done with service!");
}
servicePromise
在classA中定义为:
public static Promise servicePromise = null
;
如果我理解正确,问题是getCurrentActivity.startService(intent)
没有正确执行 。我能够在startService
之后成功返回getCurrentActivity.startService(intent)
内的承诺,所以我知道问题不在于我如何调用startService
。但是,我无法从BackgroundService
内部返回承诺,这就是我想要的。
在onHandleIntent
内部,我尝试在执行任何其他代码之前调用ClassA.servicePromise.resolve("done with service!");
,以测试它是否有效,但事实并非如此。
在我的清单中,我添加了service
,如下所示:
<service android:name="com.smaplePakcage.name.BackgroundService"
android:exported="false">
</service>