Skip to content

Commit ea6ced1

Browse files
Zhiwzibuyu1995
authored andcommitted
feat(kotlin): add android kotlin example
1 parent aee387b commit ea6ced1

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

63 files changed

+2025
-0
lines changed

mqtt-client-Android-Kotlin/.gitignore

+15
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
*.iml
2+
.gradle
3+
/local.properties
4+
/.idea/caches
5+
/.idea/libraries
6+
/.idea/modules.xml
7+
/.idea/workspace.xml
8+
/.idea/navEditor.xml
9+
/.idea/assetWizardSettings.xml
10+
.DS_Store
11+
/build
12+
/captures
13+
.externalNativeBuild
14+
.cxx
15+
local.properties

mqtt-client-Android-Kotlin/README.md

+15
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
# Android MQTT Client Examples
2+
3+
## Prerequisites
4+
5+
- Programing Language: [Kotlin](https://kotlinlang.org/)
6+
- IDE: Android Studio
7+
8+
## Libraries
9+
10+
- [Eclipse Paho Java Client](https://github.com/eclipse/paho.mqtt.java)
11+
- [Eclipse Paho Android Service](https://github.com/eclipse/paho.mqtt.android)
12+
13+
## Run
14+
15+
Open the project in Android Studio, connect the virtual machine or device, and run
+15
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
# Android 连接 MQTT 示例
2+
3+
## 准备
4+
5+
- 编程语言: [Kotlin](https://kotlinlang.org/)
6+
- 开发工具: Android Studio
7+
8+
## 依赖库
9+
10+
- [Eclipse Paho Java Client](https://github.com/eclipse/paho.mqtt.java)
11+
- [Eclipse Paho Android Service](https://github.com/eclipse/paho.mqtt.android)
12+
13+
## 运行
14+
15+
在 Android Studio 中打开项目,连接虚拟机或设备,运行
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
/build
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
plugins {
2+
id 'com.android.application'
3+
id 'org.jetbrains.kotlin.android'
4+
}
5+
6+
android {
7+
compileSdk 32
8+
9+
defaultConfig {
10+
applicationId "io.emqx.mqtt"
11+
minSdk 21
12+
targetSdk 32
13+
versionCode 1
14+
versionName "1.0"
15+
16+
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
17+
}
18+
19+
buildTypes {
20+
release {
21+
minifyEnabled false
22+
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
23+
}
24+
}
25+
compileOptions {
26+
sourceCompatibility JavaVersion.VERSION_1_8
27+
targetCompatibility JavaVersion.VERSION_1_8
28+
}
29+
kotlinOptions {
30+
jvmTarget = '1.8'
31+
}
32+
}
33+
34+
dependencies {
35+
36+
implementation 'androidx.core:core-ktx:1.8.0'
37+
implementation 'androidx.appcompat:appcompat:1.4.2'
38+
implementation 'com.google.android.material:material:1.6.1'
39+
testImplementation 'junit:junit:4.13.2'
40+
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
41+
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
42+
implementation 'org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.2.5'
43+
implementation 'org.eclipse.paho:org.eclipse.paho.android.service:1.1.1'
44+
implementation 'org.bouncycastle:bcpkix-jdk15on:1.59'
45+
implementation 'androidx.legacy:legacy-support-v4:1.0.0'
46+
47+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
# Add project specific ProGuard rules here.
2+
# You can control the set of applied configuration files using the
3+
# proguardFiles setting in build.gradle.
4+
#
5+
# For more details, see
6+
# http://developer.android.com/guide/developing/tools/proguard.html
7+
8+
# If your project uses WebView with JS, uncomment the following
9+
# and specify the fully qualified class name to the JavaScript interface
10+
# class:
11+
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
12+
# public *;
13+
#}
14+
15+
# Uncomment this to preserve the line number information for
16+
# debugging stack traces.
17+
#-keepattributes SourceFile,LineNumberTable
18+
19+
# If you keep the line number information, uncomment this to
20+
# hide the original source file name.
21+
#-renamesourcefileattribute SourceFile
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
package io.emqx.mqtt
2+
3+
import androidx.test.platform.app.InstrumentationRegistry
4+
import androidx.test.ext.junit.runners.AndroidJUnit4
5+
6+
import org.junit.Test
7+
import org.junit.runner.RunWith
8+
9+
import org.junit.Assert.*
10+
11+
/**
12+
* Instrumented test, which will execute on an Android device.
13+
*
14+
* See [testing documentation](http://d.android.com/tools/testing).
15+
*/
16+
@RunWith(AndroidJUnit4::class)
17+
class ExampleInstrumentedTest {
18+
@Test
19+
fun useAppContext() {
20+
// Context of the app under test.
21+
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
22+
assertEquals("io.emqx.mqtt", appContext.packageName)
23+
}
24+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
<?xml version="1.0" encoding="utf-8"?>
2+
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
3+
xmlns:tools="http://schemas.android.com/tools"
4+
package="io.emqx.mqtt">
5+
6+
<uses-permission android:name="android.permission.INTERNET" />
7+
<uses-permission android:name="android.permission.WAKE_LOCK" />
8+
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
9+
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
10+
11+
<application
12+
android:allowBackup="true"
13+
android:dataExtractionRules="@xml/data_extraction_rules"
14+
android:fullBackupContent="@xml/backup_rules"
15+
android:icon="@mipmap/ic_launcher"
16+
android:label="@string/app_name"
17+
android:roundIcon="@mipmap/ic_launcher_round"
18+
android:supportsRtl="true"
19+
android:theme="@style/Theme.MqttExample"
20+
tools:targetApi="31">
21+
<activity
22+
android:name=".MainActivity"
23+
android:exported="true"
24+
android:theme="@style/AppTheme.NoActionBar">
25+
<intent-filter>
26+
<action android:name="android.intent.action.MAIN" />
27+
28+
<category android:name="android.intent.category.LAUNCHER" />
29+
</intent-filter>
30+
</activity>
31+
<!-- Mqtt Service -->
32+
<service android:name="org.eclipse.paho.android.service.MqttService" />
33+
34+
</application>
35+
36+
</manifest>
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
package io.emqx.mqtt
2+
3+
import android.content.Context
4+
import android.os.Bundle
5+
import android.view.LayoutInflater
6+
import android.view.View
7+
import android.view.ViewGroup
8+
import androidx.fragment.app.Fragment
9+
import androidx.fragment.app.FragmentActivity
10+
11+
abstract class BaseFragment : Fragment() {
12+
var fragmentActivity: FragmentActivity? = null
13+
override fun onCreateView(
14+
inflater: LayoutInflater, container: ViewGroup?,
15+
savedInstanceState: Bundle?
16+
): View? {
17+
val view = inflater.inflate(layoutResId, container, false)
18+
setUpView(view)
19+
return view
20+
}
21+
22+
protected abstract val layoutResId: Int
23+
protected abstract fun setUpView(view: View)
24+
override fun onAttach(context: Context) {
25+
super.onAttach(context)
26+
fragmentActivity = activity
27+
}
28+
29+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
package io.emqx.mqtt
2+
3+
import android.content.Context
4+
import org.eclipse.paho.android.service.MqttAndroidClient
5+
import org.eclipse.paho.client.mqttv3.MqttConnectOptions
6+
7+
class Connection(
8+
private val context: Context,
9+
var host: String,
10+
var port: Int,
11+
var clientId: String,
12+
var username: String,
13+
var password: String,
14+
private val tls: Boolean
15+
) {
16+
fun getMqttAndroidClient(context: Context?): MqttAndroidClient {
17+
val uri: String = if (tls) {
18+
"ssl://$host:$port"
19+
} else {
20+
"tcp://$host:$port"
21+
}
22+
return MqttAndroidClient(context, uri, clientId)
23+
}
24+
25+
val mqttConnectOptions: MqttConnectOptions
26+
get() {
27+
val options = MqttConnectOptions()
28+
options.isCleanSession = false
29+
if (tls) {
30+
try {
31+
options.socketFactory =
32+
SSLUtils.getSingleSocketFactory(context.resources.openRawResource(R.raw.cacert))
33+
} catch (e: Exception) {
34+
e.printStackTrace()
35+
}
36+
}
37+
if (username.isNotEmpty()) {
38+
options.userName = username
39+
}
40+
if (password.isNotEmpty()) {
41+
options.password = password.toCharArray()
42+
}
43+
return options
44+
}
45+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
package io.emqx.mqtt
2+
3+
import android.util.Log
4+
import android.view.View
5+
import android.widget.Button
6+
import android.widget.EditText
7+
import android.widget.RadioButton
8+
import android.widget.Toast
9+
import org.eclipse.paho.client.mqttv3.IMqttActionListener
10+
import org.eclipse.paho.client.mqttv3.IMqttToken
11+
import org.eclipse.paho.client.mqttv3.MqttAsyncClient
12+
13+
class ConnectionFragment : BaseFragment() {
14+
private lateinit var mHost: EditText
15+
private lateinit var mPort: EditText
16+
private lateinit var mClientId: EditText
17+
private lateinit var mUsername: EditText
18+
private lateinit var mPassword: EditText
19+
private lateinit var mTlsButton: RadioButton
20+
private lateinit var mButton: Button
21+
override val layoutResId: Int
22+
get() = R.layout.fragment_connection
23+
24+
override fun setUpView(view: View) {
25+
mHost = view.findViewById(R.id.host)
26+
mHost.setText("broker.emqx.io")
27+
mPort = view.findViewById(R.id.port)
28+
mClientId = view.findViewById(R.id.clientid)
29+
mClientId.setText(MqttAsyncClient.generateClientId())
30+
mUsername = view.findViewById(R.id.username)
31+
mPassword = view.findViewById(R.id.password)
32+
mTlsButton = view.findViewById(R.id.tls_true)
33+
mButton = view.findViewById(R.id.btn_connect)
34+
mButton.setOnClickListener {
35+
if (mButton.text.toString() == getString(R.string.connect)) {
36+
val connection = Connection(
37+
fragmentActivity!!,
38+
mHost.text.toString(),
39+
mPort.text.toString().toInt(),
40+
mClientId.text.toString(),
41+
mUsername.text.toString(),
42+
mPassword.text.toString(),
43+
mTlsButton.isChecked
44+
)
45+
(fragmentActivity as MainActivity).connect(
46+
connection,
47+
object : IMqttActionListener {
48+
override fun onSuccess(asyncActionToken: IMqttToken) {
49+
Log.d(
50+
"ConnectionFragment",
51+
"Connected to: " + asyncActionToken.client.serverURI
52+
)
53+
updateButtonText()
54+
}
55+
56+
override fun onFailure(asyncActionToken: IMqttToken, exception: Throwable) {
57+
Toast.makeText(
58+
fragmentActivity,
59+
exception.toString(),
60+
Toast.LENGTH_SHORT
61+
).show()
62+
exception.printStackTrace()
63+
}
64+
})
65+
} else {
66+
(fragmentActivity as MainActivity).disconnect()
67+
}
68+
}
69+
}
70+
71+
fun updateButtonText() {
72+
if ((fragmentActivity as MainActivity).notConnected(false)) {
73+
mButton.text = getText(R.string.connect)
74+
} else {
75+
mButton.text = getString(R.string.disconnect)
76+
}
77+
}
78+
79+
companion object {
80+
fun newInstance(): ConnectionFragment {
81+
return ConnectionFragment()
82+
}
83+
}
84+
}

0 commit comments

Comments
 (0)