Android에서 mqtt 사용하기
Android 에서 mqtt프로토콜을 이용하여 통신하는 간단한 예제입니다.
mosquitto broker를 설치하는 과정도 포함합니다.
----------------------------------------------------------------------------------------------------------------
브로커 설치
https://mosquitto.org/download/ mosuitto broker를 다운받기 위해 다음의 사이트에 접속한다.
Mosquitto 설치파일을 next를 눌러 쭉 설치한다.
아래와 같이 program files 또는 설치시 지정한 경로에 mosquitto 파일이 생성된다.
아래의 mosquitto.exe 를 클릭하여 브로커를 실행한다.
*브로커 실행시 아무것도 안나오고 검은색 화면만나오는것이 정상이다.*
Android mqtt client 설치
Android 에서 mqtt client 로 paho 라이브러리를 사용한다.
App을 우클릭하여 open Module setting 에 들어간다
Dependencies 탭을 누른뒤에 우측에 + 버튼을 눌러 Library dependency를 클릭한다.
Client.mqttv3 와 android.service 를 모두 dependency에 추가한다.
Client.mqttv3 와 android.service 를 모두 dependency에 추가한다.
Gradle 에 추가된 것을 볼 수 있다.
implementation 'org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.2.0'
implementation 'org.eclipse.paho:org.eclipse.paho.android.service:1.1.1'
Android manifest에 권한과 service를 등록 하도록 한다.
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<service android:name="org.eclipse.paho.android.service.MqttService" />
Android mqtt client 소스 작성
public class MainActivity extends AppCompatActivity {
private MqttAndroidClient mqttAndroidClient;
private Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button)findViewById(R.id.button);
mqttAndroidClient = new MqttAndroidClient(this, "tcp://" + "192.168.219.103" + ":1883", MqttClient.generateClientId());
// 2번째 파라메터 : 브로커의 ip 주소 , 3번째 파라메터 : client 의 id를 지정함 여기서는 paho 의 자동으로 id를 만들어주는것
try {
IMqttToken token = mqttAndroidClient.connect(getMqttConnectionOption()); //mqtttoken 이라는것을 만들어 connect option을 달아줌
token.setActionCallback(new IMqttActionListener() {
@Override
public void onSuccess(IMqttToken asyncActionToken) {
mqttAndroidClient.setBufferOpts(getDisconnectedBufferOptions()); //연결에 성공한경우
Log.e("Connect_success", "Success");
try {
mqttAndroidClient.subscribe("jmlee", 0 ); //연결에 성공하면 jmlee 라는 토픽으로 subscribe함
} catch (MqttException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) { //연결에 실패한경우
Log.e("connect_fail", "Failure " + exception.toString());
}
});
} catch (
MqttException e)
{
e.printStackTrace();
}
/*
* subscribe 할때 3번째 파라메터에 익명함수 리스너를 달아줄수도있음
* */
/*try {
mqttAndroidClient.subscribe("jmlee!!", 0, new IMqttMessageListener() {
@Override
public void messageArrived(String topic, MqttMessage message) throws Exception {
}
});
} catch (MqttException e) {
e.printStackTrace();
}*/
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
try {
mqttAndroidClient.publish("jmlee", "hello , my name is jmlee !".getBytes(), 0 , false );
//버튼을 클릭하면 jmlee 라는 토픽으로 메시지를 보냄
} catch (MqttException e) {
e.printStackTrace();
}
}
});
mqttAndroidClient.setCallback(new MqttCallback() { //클라이언트의 콜백을 처리하는부분
@Override
public void connectionLost(Throwable cause) {
}
@Override
public void messageArrived(String topic, MqttMessage message) throws Exception { //모든 메시지가 올때 Callback method
if (topic.equals("jmlee")){ //topic 별로 분기처리하여 작업을 수행할수도있음
String msg = new String(message.getPayload());
Log.e("arrive message : ", msg);
}
}
@Override
public void deliveryComplete(IMqttDeliveryToken token) {
}
});
}
private DisconnectedBufferOptions getDisconnectedBufferOptions() {
DisconnectedBufferOptions disconnectedBufferOptions = new DisconnectedBufferOptions();
disconnectedBufferOptions.setBufferEnabled(true);
disconnectedBufferOptions.setBufferSize(100);
disconnectedBufferOptions.setPersistBuffer(true);
disconnectedBufferOptions.setDeleteOldestMessages(false);
return disconnectedBufferOptions;
}
private MqttConnectOptions getMqttConnectionOption() {
MqttConnectOptions mqttConnectOptions = new MqttConnectOptions();
mqttConnectOptions.setCleanSession(false);
mqttConnectOptions.setAutomaticReconnect(true);
mqttConnectOptions.setWill("aaa", "I am going offline".getBytes(), 1, true);
return mqttConnectOptions;
}
}
Log 에 다음과 같은 메시지를 확인가능함