在自定义 API 中启动 Activity
插件中启动新 Activity 并获取获取 Activity 返回的数据。
示例代码:
继承 BaseJsPlugin,确定自定义 API 的事件名称:
@JsPlugin(secondary = true)
public class CustomPlugin extends BaseJsPlugin {
@JsEvent("testStartActivityForResult")
public void testStartActivityForResult(final RequestEvent req) {
}
}
添加 Activity 返回监听,并在监听处理完成后移除监听:
注意:
注册监听和移除监听建议配对使用,否则会有内存泄漏的风险。
@JsPlugin(secondary = true)
public class CustomPlugin extends BaseJsPlugin {
@JsEvent("testStartActivityForResult")
public void testStartActivityForResult(final RequestEvent req) {
Activity activity = req.activityRef.get();
TmfMiniSDK.addActivityResultListener(new IActivityResultListener() {
@Override
public boolean doOnActivityResult(int requestCode, int resultCode, Intent data) {
TmfMiniSDK.removeActivityResultListener(this);
Log.i(ModuleApplet.TAG, data.getStringExtra("key"));
req.ok();
return true;
}
});
}
}
启动新的 Activity:
注意:
启动 Activity 时,requestCode 必须>=1000000,否则可能与内部 requestCode 冲突,引起未知问题。
@JsPlugin(secondary = true)
public class CustomPlugin extends BaseJsPlugin {
@JsEvent("testStartActivityForResult")
public void testStartActivityForResult(final RequestEvent req) {
Activity activity = req.activityRef.get();
TmfMiniSDK.addActivityResultListener(new IActivityResultListener() {
@Override
public boolean doOnActivityResult(int requestCode, int resultCode, Intent data) {
TmfMiniSDK.removeActivityResultListener(this);
Log.i(ModuleApplet.TAG, data.getStringExtra("key"));
req.ok();
return true;
}
});
activity.startActivityForResult(new Intent(activity, TransActivity.class), 1000000);
}
}
在自定义 API 中调用三方 App
当在自定义 API 中调用其它第三方 App(分享、支付、登录)等,当这些操作完成后能直接返回小程序而不是返回 App。
首先开发者创建透明的辅助 Activity,如下示例:
TransActivity 为定义的透明辅助 activity(透明 activity 开发者自行配置,因为主题的设置与应用 Activity 继承的系统 Activity 有关)
<activity android:name=".activity.TransActivity"
android:exported="false"
android:screenOrientation="portrait"
android:theme="@style/TransparentTheme"/>
然后在 TransActivity 中调用业务逻辑。
public class TransActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.applet_activity_tran);
Intent intent = new Intent();
intent.putExtra("key", "value");
setResult(RESULT_OK, intent);
finish();
}
}
插件启动 Activity 并监听数据返回。
@JsPlugin(secondary = true)
public class CustomPlugin extends BaseJsPlugin {
@JsEvent("testStartActivityForResult")
public void testStartActivityForResult(final RequestEvent req) {
Activity activity = req.activityRef.get();
TmfMiniSDK.addActivityResultListener(new IActivityResultListener() {
@Override
public boolean doOnActivityResult(int requestCode, int resultCode, Intent data) {
TmfMiniSDK.removeActivityResultListener(this);
Log.i(ModuleApplet.TAG, data.getStringExtra("key"));
req.ok();
return true;
}
});
activity.startActivityForResult(new Intent(activity, TransActivity.class), 1000000);
}
}
本页内容是否解决了您的问题?