简体   繁体   English

如何从 Kotlin 中的 Android 应用程序发送文本和图像?

[英]How can I tweet texts and images from an Android App in Kotlin?

What I would like to do我想做什么

I would like to tweet text and image from an Android App.我想从 Android 应用程序中发送文本和图像。

I was able to put an image to tweet on a screen of app and the app can open tweet form via a button.我能够在应用程序的屏幕上放置要推文的图像,该应用程序可以通过按钮打开推文表单。

As a reference, I checked the following former question.作为参考,我检查了以下前一个问题。

How to Share Image + Text together using ACTION_SEND in android? 如何在android中使用ACTION_SEND一起共享图像+文本?

Problem问题

Problem is set text and image data on the program are not appeared to the twitter.问题是程序上设置的文本和图像数据没有出现在推特上。

It only show blank tweet form.它只显示空白的推文表格。

How can I move these text and image from the Android app to the tweet form?如何将这些文本和图像从 Android 应用程序移动到推文表单?

Code代码

MainActivity.kt主活动.kt

package com.example.tweets

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.Toast
import android.content.Intent
import android.net.Uri
import android.util.Log
import androidx.core.app.ShareCompat
import java.io.File
import android.R.attr.path
import android.graphics.BitmapFactory
import kotlinx.android.synthetic.main.activity_main.*
import androidx.core.app.ComponentActivity.ExtraData
import androidx.core.content.ContextCompat.getSystemService
import android.icu.lang.UCharacter.GraphemeClusterBreak.T
import java.io.IOException


class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        try {resources.assets.open("sample.jpg").use { istream ->
            val bitmap = BitmapFactory.decodeStream(istream)
            sample.setImageBitmap(bitmap)
        }
        } catch (e: IOException) {
            e.printStackTrace()
        }


        val intentTweetButton: Button = findViewById(R.id.intentTweetButton)
        intentTweetButton.setOnClickListener {
            shareTwitter()
        }

        /*

        val shareCompatButton: Button = findViewById(R.id.shareCompatButton)
        shareCompatButton.setOnClickListener {
            shareCompat()
        }
        */
    }

    fun shareTwitter() {
        val message = "shareTwitter intent tweet"
        val bmpUri = Uri.parse("file://$path")
        try {
            val sharingIntent = Intent(Intent.ACTION_SEND)
            sharingIntent.setClassName("com.twitter.android", "com.twitter.android.PostActivity")
            val imageUri = Uri.parse("sample.jpg")
            sharingIntent.putExtra(Intent.EXTRA_TEXT, "Hello")
            sharingIntent.putExtra(Intent.EXTRA_STREAM, imageUri)
            sharingIntent.type = "image/jpeg"
            sharingIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
            startActivity(sharingIntent)
        }
        catch (e: Exception) {
            Log.e("In Exception", "Comes here")
            val i = Intent()
            i.putExtra(Intent.EXTRA_TEXT, message)
            i.action = Intent.ACTION_VIEW
            i.data = Uri.parse("https://mobile.twitter.com/compose/tweet")
            startActivity(i)
        }

    }

    /*

    fun shareCompat() {
        val message = "shareCompat"
        val builder = ShareCompat.IntentBuilder.from(this)
        builder.setChooserTitle("Choose App")
        builder.setText(message)
        builder.setType("text/plain")
        builder.addStream(Uri.fromFile(File("sample.jpg")))
        builder.setType("image/jpg")
        builder.startChooser()
    }
     */
}

activity_main.xml活动_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <ImageView
        android:id="@+id/sample"
        android:scaleType="centerCrop"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:contentDescription="@string/img_description"
        tools:ignore="InvalidId" />

    <Button
        android:id="@+id/intentTweetButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginTop="16dp"
        android:text="intent tweet"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <!--
    <Button
        android:id="@+id/shareCompatButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginTop="16dp"
        android:text="ShareCompat"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/intentTweetButton" />
     -->

</androidx.constraintlayout.widget.ConstraintLayout>

What I tried to do我试图做的

I tried to use share compat instead of intent , but it didn't work neither.我尝试使用share compat而不是intent ,但它也不起作用。

In addition to that, share compat is only available for user who have downloaded Twitter app on the phones, so I prefer to use intent to tweet text and image from the Android app.除此之外, share compat仅适用于在手机上下载了 Twitter 应用程序的用户,因此我更喜欢使用intent从 Android 应用程序中发送文本和图像。

The image is located on app/assets/sample.jpg .该图像位于app/assets/sample.jpg

Environment环境

Android Studio 3.5.3安卓工作室 3.5.3

Kotlin plugin 1.3.50 Kotlin 插件 1.3.50

try this尝试这个

 private void shareTwitter(String message) {
    Intent tweetIntent = new Intent(Intent.ACTION_SEND);
    tweetIntent.putExtra(Intent.EXTRA_TEXT, "This is a Test.");
    tweetIntent.setType("text/plain");

    PackageManager packManager = getPackageManager();
    List<ResolveInfo> resolvedInfoList = packManager.queryIntentActivities(tweetIntent, PackageManager.MATCH_DEFAULT_ONLY);

    boolean resolved = false;
    for (ResolveInfo resolveInfo : resolvedInfoList) {
        if (resolveInfo.activityInfo.packageName.startsWith("com.twitter.android")) {
            tweetIntent.setClassName(
                    resolveInfo.activityInfo.packageName,
                    resolveInfo.activityInfo.name);
            resolved = true;
            break;
        }
    }
    if (resolved) {
        startActivity(tweetIntent);
    } else {
        Intent i = new Intent();
        i.putExtra(Intent.EXTRA_TEXT, message);
        i.setAction(Intent.ACTION_VIEW);
        i.setData(Uri.parse("https://twitter.com/intent/tweet?text=" + urlEncode(message)));
        startActivity(i);
        Toast.makeText(this, "Twitter app isn't found", Toast.LENGTH_LONG).show();
    }
}

private String urlEncode(String s) {
    try {
        return URLEncoder.encode(s, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        Log.wtf(TAG, "UTF-8 should always be supported", e);
        return "";
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何修复 XML 中阻止在 Android Studio 上显示预览或运行应用程序的错误(红色文本)? - How can I fix errors (red texts) in XML which are preventing from showing preview or running the app on Android Studio? 如何在Android Studio中将图像与文本链接? - How to link images with texts in android studio? 如何从套接字 Kotlin/Android 读取文本? - How can i read text from socket Kotlin/Android? 如何从Java代码向Android App添加图像 - How can you add images to Android App from java code 如何在TextView或任何其他可以包含文本和媒体的视图中显示视频和图像,但Webview除外 - How can I display Video and Images in TextView or any other View that can contain texts and media except webview 如何使用twitter4j显示来自Twitter帐户的推文并使用Android应用程序发送相同的帐户? - How to display tweets from a twitter account and tweet that same account from an android app using twitter4j? 通过在Android上的Twitter应用程序上单击推文来打开应用程序 - Open a app by clicking on a tweet from twitter app on android 在Android ListView中的文本旁边显示来自REST服务的图像 - Display Images from REST service beside texts in Android ListView 如何从Firebase下载各种类型的文件(图像,视频,文本)并显示它们 - How do I download various types of files(images, videos , texts) from Firebase and display them Android:如何从Android应用程序获取IP地址? - Android: How can I get ip address from an android app?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM