Skip to content

Commit 45b9b60

Browse files
share: Support sharing content received from other apps on Android
Enables the app to receive arbitrary content from other apps via advertising Android Intent filters in AndroidManifest. It allows the OS to list our app in the platform share sheet. Adds handlers for the two Intent actions, namely SEND and SEND_MULTIPLE. Handling all three possible combinations: - Receiving only a text - Receiving only a file (or multiple files in case of SEND_MULTIPLE) - Receiving both the file (or multiple) and the accompanying text. The Android side Kotlin implementation is adapted from the legacy app's implementation, with only difference being that the legacy app didn't handle the 3rd case mentioned above, see: https://github.com/zulip/zulip-mobile/blob/eb8505c4a/android/app/src/main/java/com/zulipmobile/sharing/SharingHelper.kt To allow sending Android Intent events from Kotlin to Dart, Pigeon's EventChannelApi is used. For which the registration happens in `MainActivity.configureFlutterEngine`, this bit of code was adapted from Pigeon's Android example, see: https://github.com/flutter/packages/blob/b2aef15c1/packages/pigeon/example/app/android/app/src/main/kotlin/dev/flutter/pigeon_example_app/MainActivity.kt#L109-L121
1 parent 91b9335 commit 45b9b60

28 files changed

+985
-7
lines changed

android/app/src/main/AndroidManifest.xml

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,16 @@
3636
<category android:name="android.intent.category.BROWSABLE" />
3737
<data android:scheme="zulip" android:host="login" />
3838
</intent-filter>
39+
<intent-filter>
40+
<action android:name="android.intent.action.SEND" />
41+
<category android:name="android.intent.category.DEFAULT" />
42+
<data android:mimeType="*/*" />
43+
</intent-filter>
44+
<intent-filter>
45+
<action android:name="android.intent.action.SEND_MULTIPLE" />
46+
<category android:name="android.intent.category.DEFAULT" />
47+
<data android:mimeType="*/*" />
48+
</intent-filter>
3949
</activity>
4050
<!-- Don't delete the meta-data below.
4151
This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
Lines changed: 112 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,112 @@
1+
package com.zulip.flutter
2+
3+
import android.content.Context
4+
import android.content.Intent
5+
import android.net.Uri
6+
import android.provider.OpenableColumns
7+
8+
class AndroidIntentEventListener : AndroidIntentEventsStreamHandler() {
9+
private var eventSink: PigeonEventSink<AndroidIntentEvent>? = null
10+
private val buffer = mutableListOf<AndroidIntentEvent>()
11+
12+
override fun onListen(p0: Any?, sink: PigeonEventSink<AndroidIntentEvent>) {
13+
eventSink = sink
14+
buffer.forEach { eventSink!!.success(it) }
15+
}
16+
17+
private fun onEvent(event: AndroidIntentEvent) {
18+
if (eventSink != null) {
19+
eventSink?.success(event)
20+
} else {
21+
buffer.add(event)
22+
}
23+
}
24+
25+
fun handleSend(context: Context, intent: Intent) {
26+
val intentAction = intent.action
27+
assert(
28+
intentAction == Intent.ACTION_SEND
29+
|| intentAction == Intent.ACTION_SEND_MULTIPLE
30+
)
31+
32+
// EXTRA_TEXT and EXTRA_STREAM are the text and file components of the
33+
// content, respectively. The ACTION_SEND{,_MULTIPLE} docs say
34+
// "either" / "or" will be present:
35+
// https://developer.android.com/reference/android/content/Intent#ACTION_SEND
36+
// But empirically both can be present, commonly, so we accept that form,
37+
// interpreting it as an intent to share both kinds of data.
38+
//
39+
// Empirically, sometimes EXTRA_TEXT isn't something we think needs to be
40+
// shared, like the URL of a file that's present in EXTRA_STREAM… but we
41+
// shrug and include it anyway because we don't want to second-guess other
42+
// apps' decisions about what to include; it's their responsibility.
43+
44+
val extraText = intent.getStringExtra(Intent.EXTRA_TEXT)
45+
val extraStream = when (intentAction) {
46+
Intent.ACTION_SEND -> {
47+
var extraStream: List<IntentSharedFile>? = null
48+
// TODO(android-sdk-33) Remove the use of deprecated API.
49+
@Suppress("DEPRECATION") val url = intent.getParcelableExtra<Uri>(Intent.EXTRA_STREAM)
50+
if (url != null) {
51+
extraStream = listOf(getIntentSharedFile(context, url))
52+
}
53+
extraStream
54+
}
55+
56+
Intent.ACTION_SEND_MULTIPLE -> {
57+
var extraStream: MutableList<IntentSharedFile>? = null
58+
// TODO(android-sdk-33) Remove the use of deprecated API.
59+
@Suppress("DEPRECATION") val urls =
60+
intent.getParcelableArrayListExtra<Uri>(Intent.EXTRA_STREAM)
61+
if (urls != null) {
62+
extraStream = mutableListOf()
63+
for (url in urls) {
64+
val sharedFile = getIntentSharedFile(context, url)
65+
extraStream.add(sharedFile)
66+
}
67+
}
68+
extraStream
69+
}
70+
71+
else -> throw IllegalArgumentException("Unexpected value for intent.action: $intentAction")
72+
}
73+
74+
if (extraText == null && extraStream == null) {
75+
throw Exception("Got unexpected ACTION_SEND* intent, with neither EXTRA_TEXT nor EXTRA_STREAM")
76+
}
77+
78+
onEvent(
79+
AndroidIntentSendEvent(
80+
action = intentAction,
81+
extraText = extraText,
82+
extraStream = extraStream,
83+
)
84+
)
85+
}
86+
}
87+
88+
// A helper function to retrieve the shared file from the `content://` URL
89+
// from the ACTION_SEND{_MULTIPLE} intent.
90+
fun getIntentSharedFile(context: Context, url: Uri): IntentSharedFile {
91+
val contentResolver = context.contentResolver
92+
val mimeType = contentResolver.getType(url)
93+
val name = contentResolver.query(url, null, null, null, null)?.use { cursor ->
94+
cursor.moveToFirst()
95+
val nameIndex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)
96+
cursor.getString(nameIndex)
97+
} ?: ("unknown." + (mimeType?.split('/')?.last() ?: "bin"))
98+
99+
class ResolverFailedException(msg: String) : RuntimeException(msg)
100+
101+
val bytes = (contentResolver.openInputStream(url)
102+
?: throw ResolverFailedException("resolver.open… failed"))
103+
.use { inputStream ->
104+
inputStream.readBytes()
105+
}
106+
107+
return IntentSharedFile(
108+
name = name,
109+
mimeType = mimeType,
110+
bytes = bytes
111+
)
112+
}
Lines changed: 203 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,203 @@
1+
// Autogenerated from Pigeon (v25.5.0), do not edit directly.
2+
// See also: https://pub.dev/packages/pigeon
3+
@file:Suppress("UNCHECKED_CAST", "ArrayInDataClass")
4+
5+
package com.zulip.flutter
6+
7+
import android.util.Log
8+
import io.flutter.plugin.common.BasicMessageChannel
9+
import io.flutter.plugin.common.BinaryMessenger
10+
import io.flutter.plugin.common.EventChannel
11+
import io.flutter.plugin.common.MessageCodec
12+
import io.flutter.plugin.common.StandardMethodCodec
13+
import io.flutter.plugin.common.StandardMessageCodec
14+
import java.io.ByteArrayOutputStream
15+
import java.nio.ByteBuffer
16+
private object AndroidIntentsPigeonUtils {
17+
fun deepEquals(a: Any?, b: Any?): Boolean {
18+
if (a is ByteArray && b is ByteArray) {
19+
return a.contentEquals(b)
20+
}
21+
if (a is IntArray && b is IntArray) {
22+
return a.contentEquals(b)
23+
}
24+
if (a is LongArray && b is LongArray) {
25+
return a.contentEquals(b)
26+
}
27+
if (a is DoubleArray && b is DoubleArray) {
28+
return a.contentEquals(b)
29+
}
30+
if (a is Array<*> && b is Array<*>) {
31+
return a.size == b.size &&
32+
a.indices.all{ deepEquals(a[it], b[it]) }
33+
}
34+
if (a is List<*> && b is List<*>) {
35+
return a.size == b.size &&
36+
a.indices.all{ deepEquals(a[it], b[it]) }
37+
}
38+
if (a is Map<*, *> && b is Map<*, *>) {
39+
return a.size == b.size && a.all {
40+
(b as Map<Any?, Any?>).containsKey(it.key) &&
41+
deepEquals(it.value, b[it.key])
42+
}
43+
}
44+
return a == b
45+
}
46+
47+
}
48+
49+
/** Generated class from Pigeon that represents data sent in messages. */
50+
data class IntentSharedFile (
51+
val name: String,
52+
val mimeType: String? = null,
53+
val bytes: ByteArray
54+
)
55+
{
56+
companion object {
57+
fun fromList(pigeonVar_list: List<Any?>): IntentSharedFile {
58+
val name = pigeonVar_list[0] as String
59+
val mimeType = pigeonVar_list[1] as String?
60+
val bytes = pigeonVar_list[2] as ByteArray
61+
return IntentSharedFile(name, mimeType, bytes)
62+
}
63+
}
64+
fun toList(): List<Any?> {
65+
return listOf(
66+
name,
67+
mimeType,
68+
bytes,
69+
)
70+
}
71+
override fun equals(other: Any?): Boolean {
72+
if (other !is IntentSharedFile) {
73+
return false
74+
}
75+
if (this === other) {
76+
return true
77+
}
78+
return AndroidIntentsPigeonUtils.deepEquals(toList(), other.toList()) }
79+
80+
override fun hashCode(): Int = toList().hashCode()
81+
}
82+
83+
/**
84+
* Generated class from Pigeon that represents data sent in messages.
85+
* This class should not be extended by any user class outside of the generated file.
86+
*/
87+
sealed class AndroidIntentEvent
88+
/** Generated class from Pigeon that represents data sent in messages. */
89+
data class AndroidIntentSendEvent (
90+
val action: String,
91+
val extraText: String? = null,
92+
val extraStream: List<IntentSharedFile>? = null
93+
) : AndroidIntentEvent()
94+
{
95+
companion object {
96+
fun fromList(pigeonVar_list: List<Any?>): AndroidIntentSendEvent {
97+
val action = pigeonVar_list[0] as String
98+
val extraText = pigeonVar_list[1] as String?
99+
val extraStream = pigeonVar_list[2] as List<IntentSharedFile>?
100+
return AndroidIntentSendEvent(action, extraText, extraStream)
101+
}
102+
}
103+
fun toList(): List<Any?> {
104+
return listOf(
105+
action,
106+
extraText,
107+
extraStream,
108+
)
109+
}
110+
override fun equals(other: Any?): Boolean {
111+
if (other !is AndroidIntentSendEvent) {
112+
return false
113+
}
114+
if (this === other) {
115+
return true
116+
}
117+
return AndroidIntentsPigeonUtils.deepEquals(toList(), other.toList()) }
118+
119+
override fun hashCode(): Int = toList().hashCode()
120+
}
121+
private open class AndroidIntentsPigeonCodec : StandardMessageCodec() {
122+
override fun readValueOfType(type: Byte, buffer: ByteBuffer): Any? {
123+
return when (type) {
124+
129.toByte() -> {
125+
return (readValue(buffer) as? List<Any?>)?.let {
126+
IntentSharedFile.fromList(it)
127+
}
128+
}
129+
130.toByte() -> {
130+
return (readValue(buffer) as? List<Any?>)?.let {
131+
AndroidIntentSendEvent.fromList(it)
132+
}
133+
}
134+
else -> super.readValueOfType(type, buffer)
135+
}
136+
}
137+
override fun writeValue(stream: ByteArrayOutputStream, value: Any?) {
138+
when (value) {
139+
is IntentSharedFile -> {
140+
stream.write(129)
141+
writeValue(stream, value.toList())
142+
}
143+
is AndroidIntentSendEvent -> {
144+
stream.write(130)
145+
writeValue(stream, value.toList())
146+
}
147+
else -> super.writeValue(stream, value)
148+
}
149+
}
150+
}
151+
152+
val AndroidIntentsPigeonMethodCodec = StandardMethodCodec(AndroidIntentsPigeonCodec())
153+
154+
155+
private class AndroidIntentsPigeonStreamHandler<T>(
156+
val wrapper: AndroidIntentsPigeonEventChannelWrapper<T>
157+
) : EventChannel.StreamHandler {
158+
var pigeonSink: PigeonEventSink<T>? = null
159+
160+
override fun onListen(p0: Any?, sink: EventChannel.EventSink) {
161+
pigeonSink = PigeonEventSink<T>(sink)
162+
wrapper.onListen(p0, pigeonSink!!)
163+
}
164+
165+
override fun onCancel(p0: Any?) {
166+
pigeonSink = null
167+
wrapper.onCancel(p0)
168+
}
169+
}
170+
171+
interface AndroidIntentsPigeonEventChannelWrapper<T> {
172+
open fun onListen(p0: Any?, sink: PigeonEventSink<T>) {}
173+
174+
open fun onCancel(p0: Any?) {}
175+
}
176+
177+
class PigeonEventSink<T>(private val sink: EventChannel.EventSink) {
178+
fun success(value: T) {
179+
sink.success(value)
180+
}
181+
182+
fun error(errorCode: String, errorMessage: String?, errorDetails: Any?) {
183+
sink.error(errorCode, errorMessage, errorDetails)
184+
}
185+
186+
fun endOfStream() {
187+
sink.endOfStream()
188+
}
189+
}
190+
191+
abstract class AndroidIntentEventsStreamHandler : AndroidIntentsPigeonEventChannelWrapper<AndroidIntentEvent> {
192+
companion object {
193+
fun register(messenger: BinaryMessenger, streamHandler: AndroidIntentEventsStreamHandler, instanceName: String = "") {
194+
var channelName: String = "dev.flutter.pigeon.zulip.AndroidIntentsEventChannelApi.androidIntentEvents"
195+
if (instanceName.isNotEmpty()) {
196+
channelName += ".$instanceName"
197+
}
198+
val internalStreamHandler = AndroidIntentsPigeonStreamHandler<AndroidIntentEvent>(streamHandler)
199+
EventChannel(messenger, channelName, AndroidIntentsPigeonMethodCodec).setStreamHandler(internalStreamHandler)
200+
}
201+
}
202+
}
203+
Lines changed: 37 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,42 @@
11
package com.zulip.flutter
22

3+
import android.content.Intent
34
import io.flutter.embedding.android.FlutterActivity
5+
import io.flutter.embedding.engine.FlutterEngine
46

5-
class MainActivity: FlutterActivity() {
7+
class MainActivity : FlutterActivity() {
8+
private var androidIntentEventListener: AndroidIntentEventListener? = null
9+
10+
override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
11+
super.configureFlutterEngine(flutterEngine)
12+
13+
androidIntentEventListener = AndroidIntentEventListener()
14+
AndroidIntentEventsStreamHandler.register(
15+
flutterEngine.dartExecutor.binaryMessenger,
16+
androidIntentEventListener!!
17+
)
18+
maybeHandleIntent(intent)
19+
}
20+
21+
override fun onNewIntent(intent: Intent) {
22+
if (maybeHandleIntent(intent)) {
23+
return
24+
}
25+
super.onNewIntent(intent)
26+
}
27+
28+
/** Returns true just if we did handle the intent. */
29+
private fun maybeHandleIntent(intent: Intent?): Boolean {
30+
intent ?: return false
31+
when (intent.action) {
32+
// Share-to-Zulip
33+
Intent.ACTION_SEND, Intent.ACTION_SEND_MULTIPLE -> {
34+
androidIntentEventListener!!.handleSend(this, intent)
35+
return true
36+
}
37+
38+
// For other intents, let Flutter handle it.
39+
else -> return false
40+
}
41+
}
642
}

0 commit comments

Comments
 (0)