[英]React-Native Android - Get the variables from intent
我正在使用 Intent 來啟動我的 React-Native 應用程序,並且我試圖找出如何獲取我在 React Native 代碼中放置在我的 Intent 上的變量。 這是否可以從 react-native 內部實現,還是我必須編寫一些 Java 代碼才能獲得它?
我用來啟動應用程序的代碼:
Intent intent = new Intent(this, MainActivity.class);
Intent.putExtra("alarm",true);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
謝謝!
試試這個以在 react-native 應用程序中獲取 Intent 參數。
在我的本機應用程序中,我使用以下代碼:
Intent launchIntent = getPackageManager().getLaunchIntentForPackage("com.my.react.app.package");
launchIntent.putExtra("test", "12331");
startActivity(launchIntent);
在本機項目中,我的 MainActivity.java
public class MainActivity extends ReactActivity {
@Override
protected String getMainComponentName() {
return "FV";
}
public static class TestActivityDelegate extends ReactActivityDelegate {
private static final String TEST = "test";
private Bundle mInitialProps = null;
private final
@Nullable
Activity mActivity;
public TestActivityDelegate(Activity activity, String mainComponentName) {
super(activity, mainComponentName);
this.mActivity = activity;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
Bundle bundle = mActivity.getIntent().getExtras();
if (bundle != null && bundle.containsKey(TEST)) {
mInitialProps = new Bundle();
mInitialProps.putString(TEST, bundle.getString(TEST));
}
super.onCreate(savedInstanceState);
}
@Override
protected Bundle getLaunchOptions() {
return mInitialProps;
}
}
@Override
protected ReactActivityDelegate createReactActivityDelegate() {
return new TestActivityDelegate(this, getMainComponentName());
}
}
在我的第一個容器中,我在 this.props 中獲得了參數
export default class App extends Component {
render() {
console.log('App props', this.props);
//...
}
}
我在這里找到的完整示例: http : //cmichel.io/how-to-set-initial-props-in-react-native/
您可以將初始道具作為包傳遞給startReactApplication
方法中的第三個參數,如下所示:
Bundle initialProps = new Bundle();
initialProps.putString("alarm", true);
mReactRootView.startReactApplication( mReactInstanceManager, "HelloWorld", initialProps );
有關更多詳細信息,請參閱此答案: https : //stackoverflow.com/a/34226172/293280
我認為這是基於@Eduardo Junior 的回答的更正確的方法
class MainDelegate(activity: ReactActivity, mainComponentName: String?) :
ReactActivityDelegate(activity, mainComponentName) {
private var params: Bundle? = null
override fun onCreate(savedInstanceState: Bundle?) {
params = plainActivity.intent.extras
super.onCreate(savedInstanceState)
}
override fun onNewIntent(intent: Intent?): Boolean {
params = intent?.extras
return super.onNewIntent(intent)
}
override fun getLaunchOptions() = params
}
class MainActivity : ReactActivity() {
/**
* Returns the name of the main component registered from JavaScript. This is used to schedule
* rendering of the component.
*/
override fun getMainComponentName() = "example"
override fun createReactActivityDelegate(): ReactActivityDelegate {
return MainDelegate(this, mainComponentName)
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.