package com.frost.mqtttutorial;
import android.Manifest;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.github.mikephil.charting.charts.LineChart;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallbackExtended;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import helpers.ChartHelper;
import helpers.MqttHelper;
public class MainActivity extends AppCompatActivity {
MqttHelper mqttHelper;
ChartHelper mChart;
LineChart chart;
TextView dataReceived;
EditText textMessage;
Button publishMessage, stop, btnLoc;
private AlarmManager manager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dataReceived = (TextView) findViewById(R.id.dataReceived);
textMessage = (EditText) findViewById(R.id.textMessage);
publishMessage = (Button) findViewById(R.id.publishMessage);
publishMessage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent alarmIntent = new Intent(MainActivity.this, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, alarmIntent, 0);
manager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
manager.setInexactRepeating(AlarmManager.RTC_WAKEUP, 0,10000, pendingIntent);
String msg = textMessage.getText().toString();
mqttHelper.publishTopic(msg);
}
});
startMqtt();
stop=(Button) findViewById(R.id.stop);
stop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent1 = new Intent(MainActivity.this, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, intent1, 0);
AlarmManager manager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
manager.cancel(pendingIntent);
Toast.makeText(v.getContext(), "Cancelled alarm", Toast.LENGTH_SHORT).show();
}
});
}
private void startMqtt(){
mqttHelper = new MqttHelper(getApplicationContext());
mqttHelper.mqttAndroidClient.setCallback(new MqttCallbackExtended() {
@Override
public void connectComplete(boolean b, String s) {
Toast.makeText(MainActivity.this,"Connected",Toast.LENGTH_LONG).show();
}
@Override
public void connectionLost(Throwable throwable) {
Toast.makeText(MainActivity.this,"Connection failed",Toast.LENGTH_LONG).show();
}
@Override
public void messageArrived(String topic, MqttMessage mqttMessage) throws Exception {
Log.w("Debug",mqttMessage.toString());
dataReceived.setText(mqttMessage.toString());
mChart.addEntry(Float.valueOf(mqttMessage.toString()));
}
@Override
public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
}
});
}
}
下面的代码用于连接到服务器并发布消息
package helpers;
import android.content.Context;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import com.frost.mqtttutorial.AlarmReceiver;
import org.eclipse.paho.android.service.MqttAndroidClient;
import org.eclipse.paho.client.mqttv3.DisconnectedBufferOptions;
import org.eclipse.paho.client.mqttv3.IMqttActionListener;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.IMqttToken;
import org.eclipse.paho.client.mqttv3.MqttCallbackExtended;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
public class MqttHelper {
public MqttAndroidClient mqttAndroidClient;
final String serverUri = "";
final String clientId ="";
final String subscriptionTopic = "";
final String publishTopic = "";
final String username = "";
final String password = "";
public MqttHelper(Context context){
mqttAndroidClient = new MqttAndroidClient(context, serverUri, clientId);
mqttAndroidClient.setCallback(new MqttCallbackExtended() {
@Override
public void connectComplete(boolean b, String s) {
Log.w("mqtt", s);
}
@Override
public void connectionLost(Throwable throwable) {
}
@Override
public void messageArrived(String topic, MqttMessage mqttMessage) throws Exception {
Log.w("Mqtt", mqttMessage.toString());
}
@Override
public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
}
});
connect();
}
public void setCallback(MqttCallbackExtended callback) {
mqttAndroidClient.setCallback(callback);
}
private void connect(){
MqttConnectOptions mqttConnectOptions = new MqttConnectOptions();
mqttConnectOptions.setAutomaticReconnect(true);
mqttConnectOptions.setCleanSession(false);
mqttConnectOptions.setUserName(username);
mqttConnectOptions.setPassword(password.toCharArray());
try {
mqttAndroidClient.connect(mqttConnectOptions, null, new IMqttActionListener() {
@Override
public void onSuccess(IMqttToken asyncActionToken) {
DisconnectedBufferOptions disconnectedBufferOptions = new DisconnectedBufferOptions();
disconnectedBufferOptions.setBufferEnabled(true);
disconnectedBufferOptions.setBufferSize(100);
disconnectedBufferOptions.setPersistBuffer(false);
disconnectedBufferOptions.setDeleteOldestMessages(false);
mqttAndroidClient.setBufferOpts(disconnectedBufferOptions);
subscribeToTopic();
}
@Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
Log.w("Mqtt", "Failed to connect to: " + serverUri + exception.toString());
}
});
} catch (MqttException ex){
ex.printStackTrace();
}
}
private void subscribeToTopic() {
try {
mqttAndroidClient.subscribe(subscriptionTopic, 0, null, new IMqttActionListener() {
@Override
public void onSuccess(IMqttToken asyncActionToken) {
Log.w("Mqtt","Subscribed!");
}
@Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
Log.w("Mqtt", "Subscribed fail!");
}
});
} catch (MqttException ex) {
System.err.println("Exception whilst subscribing");
ex.printStackTrace();
}
}
public void publishTopic(String msg) {
MqttMessage message = new MqttMessage();
message.setRetained(true);
message.setPayload(msg.getBytes());
try {
mqttAndroidClient.publish(publishTopic, message);
} catch (MqttException e) {
e.printStackTrace();
}
}
}
`
这是下面的用于通过广播接收器发送消息的代码
package com.frost.mqtttutorial;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.net.ConnectivityManager;
import android.os.SystemClock;
import android.util.Log;
import android.widget.Toast;
import org.eclipse.paho.android.service.MqttAndroidClient;
import org.eclipse.paho.client.mqttv3.DisconnectedBufferOptions;
import org.eclipse.paho.client.mqttv3.IMqttActionListener;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.IMqttToken;
import org.eclipse.paho.client.mqttv3.MqttCallbackExtended;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import helpers.MqttHelper;
public class AlarmReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent){
Log.d("Alarm", "Alarm receive");
}
}
最佳答案
Handler
以执行每个10 second
。
Handler handler = new Handler();
Runnable test = new Runnable() {
@Override
public void run() {
//do work
//String msg = textMessage.getText().toString();
// send message to server
handler.post(test, 10000); //wait 10 sec and run again
}
};
public void stopTest() {
handler.removeCallbacks(test);
}
public void startTest() {
handler.post(test,0); //wait 0 ms and run
}
参考:https://stackoverflow.com/a/41395577/9909365
关于java - 如何使用广播接收器警报管理器每10秒将文本发送到服务器,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53665354/