【问题标题】:Receive data from other app through intent-filter kotlin?通过intent-filter kotlin从其他应用程序接收数据?
【发布时间】:2021-06-30 11:08:03
【问题描述】:

主活动

 val isActivityLaunchedFromActionSend = intent?.action == Intent.ACTION_SEND
    val isActivityLaunchedFromActionSendMultiple = intent?.action == Intent.ACTION_SEND_MULTIPLE
    val isTextData = intent.type?.startsWith("text/") == true
    val isImageData = intent.type?.startsWith("image/") == true
    if (isActivityLaunchedFromActionSend && isTextData) {

        // Session 1: Handle received text data
        val sentString = intent.getStringExtra(Intent.EXTRA_TEXT)

       //Sending data to fragment so we can set the value in edittext.
        val bundle = Bundle()
        bundle.putString("message", sentString)

        val fragInfo = HomeFragment()
        fragInfo.setArguments(bundle)
      
    } else if (isActivityLaunchedFromActionSend && isImageData) {

        // Session 2: Handle received image data
        val sentImageURI = intent.getParcelableExtra<Parcelable>(Intent.EXTRA_STREAM) as? Uri

    } else if (isActivityLaunchedFromActionSendMultiple && isImageData) {
        val imageURIList = intent.getParcelableArrayListExtra<Parcelable>(Intent.EXTRA_STREAM) ?: arrayListOf()           
    }

首页片段

  override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)

    val myValue =requireArguments().getString("message")
    etUrl.setText(myValue)
   

这里 myValue 中的值将变为 null。而在 HomeFragment 中有一个 editText 所以当用户向我的应用发送链接时,该链接将自动在 EditText 中过去。

清单

  <intent-filter>
            <action android:name="android.intent.action.SEND" />
            <category android:name="android.intent.category.DEFAULT" />
            <data android:mimeType="text/plain" />

那么你能告诉我我缺少什么吗?

【问题讨论】:

    标签: android android-intent intentfilter android-jetpack-navigation


    【解决方案1】:

    您从不使用HomeFragment。在if 块中,您有val fragInfo = HomeFragment(),将参数放在该片段上......然后永远不要对fragInfo 做任何事情。因此,HomeFragment 实例及其参数将被垃圾回收。

    【讨论】:

    • 我无法理解您到底想说什么,所以如果可能的话您可以更改代码吗?
    • @BhavyaVarmora:“如果可能的话,您可以更改代码吗?” - 不,因为代码不在您的问题中。在某处,您创建了 两个 HomeFragment 实例。一个——在你的第一个代码 sn-p 中显示的那个——是没用的,因为你什么都不做。第二个是实际设置你的 UI 的那个,它没有你的文本的参数。找到第二个 HomeFragment 的创建位置,然后决定如何将该代码与第一个代码 sn-p 中的内容合并。
    猜你喜欢
    • 2015-05-02
    • 2023-02-04
    • 2014-05-11
    • 2017-04-26
    • 2019-06-04
    • 2018-11-06
    • 1970-01-01
    • 1970-01-01
    • 2012-12-26
    相关资源
    最近更新 更多