Skip to content

Commit c28990a

Browse files
Add ShareUtils
1 parent 131f481 commit c28990a

File tree

1 file changed

+69
-0
lines changed

1 file changed

+69
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
package com.termux.app.utils;
2+
3+
import android.content.ClipData;
4+
import android.content.ClipboardManager;
5+
import android.content.Context;
6+
import android.content.Intent;
7+
8+
import androidx.core.content.ContextCompat;
9+
10+
import com.termux.R;
11+
12+
public class ShareUtils {
13+
14+
/**
15+
* Open the system app chooser that allows the user to select which app to send the intent.
16+
*
17+
* @param context The context for operations.
18+
* @param intent The intent that describes the choices that should be shown.
19+
* @param title The title for choose menu.
20+
*/
21+
private static void openSystemAppChooser(final Context context, final Intent intent, final String title) {
22+
if(context == null) return;
23+
24+
final Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
25+
chooserIntent.putExtra(Intent.EXTRA_INTENT, intent);
26+
chooserIntent.putExtra(Intent.EXTRA_TITLE, title);
27+
chooserIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
28+
context.startActivity(chooserIntent);
29+
}
30+
31+
/**
32+
* Share text.
33+
*
34+
* @param context The context for operations.
35+
* @param subject The subject for sharing.
36+
* @param text The text to share.
37+
*/
38+
public static void shareText(final Context context, final String subject, final String text) {
39+
if(context == null) return;
40+
41+
final Intent shareTextIntent = new Intent(Intent.ACTION_SEND);
42+
shareTextIntent.setType("text/plain");
43+
shareTextIntent.putExtra(Intent.EXTRA_SUBJECT, subject);
44+
shareTextIntent.putExtra(Intent.EXTRA_TEXT, text);
45+
46+
openSystemAppChooser(context, shareTextIntent, context.getString(R.string.share_with));
47+
}
48+
49+
/**
50+
* Copy the text to clipboard.
51+
*
52+
* @param context The context for operations.
53+
* @param text The text to copy.
54+
* @param toastString If this is not {@code null} or empty, then a toast is shown if copying to
55+
* clipboard is successful.
56+
*/
57+
public static void copyTextToClipboard(final Context context, final String text, final String toastString) {
58+
if(context == null) return;
59+
60+
final ClipboardManager clipboardManager = ContextCompat.getSystemService(context, ClipboardManager.class);
61+
62+
if (clipboardManager != null) {
63+
clipboardManager.setPrimaryClip(ClipData.newPlainText(null, text));
64+
if (toastString != null && !toastString.isEmpty())
65+
Logger.showToast(context, toastString, true);
66+
}
67+
}
68+
69+
}

0 commit comments

Comments
 (0)