我正在尝试从我的设备中使用NFC硬件。但是,问题是当我注册Activity以接收Intent时:
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
我在Activity中收到结果而不是片段。有没有办法在Fragment中处理这个结果?
提前致谢!
答案 0 :(得分:10)
onNewIntent
属于Activity,所以你不能在你的片段中拥有它。您可以做的是在数据到达onNewIntent
时将数据传递给您的片段,前提是您有片段的引用。
Fragment fragment;
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
// Check if the fragment is an instance of the right fragment
if (fragment instanceof MyNFCFragment) {
MyNFCFragment my = (MyNFCFragment) fragment;
// Pass intent or its data to the fragment's method
my.processNFC(intent.getStringExtra());
}
}
答案 1 :(得分:0)
我通过以下方式解决了问题:
在MyActivity.java
中@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
setIntent(intent);
}
在MyFragment.java
中@Override
public void onStart() {
super.onStart();
if (getActivity() != null && getActivity().getIntent().hasExtra(...)) {
// do whatever needed
}
}
答案 2 :(得分:0)
通过在server{
listen 3000;
root /path_to_apps_public_folder;
location /{
try_files $uri $uri/ =404;
}
}
中添加以下内容,我们以更加动态的方式处理了呼叫以支持任何片段:
Activity
以及随后在任何所需的// ...
public class ActivityMain extends AppCompatActivity {
// ...
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
Fragment fragment = getFragment();
if (fragment != null) {
try {
Method method = fragment.getClass().getMethod("onNewIntent", Intent.class);
method.invoke(fragment, intent);
} catch (NoSuchMethodException ignored) {
} catch (IllegalAccessException | InvocationTargetException e) {
Log.e(TAG, "Failed to call onNewIntent method for class: " + fragment.getClass().getSimpleName());
}
}
}
public Fragment getFragment() {
//if (BuildConfig.UI_NAVIGATION_DRAWER) {
FragmentManager manager = this.getSupportFragmentManager();
manager.executePendingTransactions();
return manager.findFragmentById(R.id.my_main_content);
//} else {
// TODO: Handle view pager.
//}
}
}
实施中:
Fragment
答案 3 :(得分:0)
使用 LiveData
:
存储库:
class IntentRepo {
private val _intent = MutableLiveData<Intent>()
val get: LiveData<Intent> = Transformations.map(_intent) { it!! }
fun set(intent: Intent) { _intent.value = intent }
}
活动视图模型:
class MainViewModel(intentRepo: IntentRepo) : ViewModel() {
val intent = intentRepo
}
活动
override fun onNewIntent(intent: Intent?) {
super.onNewIntent(intent)
viewModel.intent.set(intent)
}
片段
viewModel.intent.get.observe(viewLifecycleOwner, {
// Your intent: $it
})