我正在尝试将数据从服务传递到活动并更新列表视图。
服务:
public class mqtt_service extends Service {
final String serverUri = "tcp://192.xxx.x.xx:1883";
private static final String TAG = "MQTTService";
private static final String Topic = "test";
MqttAndroidClient client;
public mqtt_service() { }
@Override
public int onStartCommand(Intent intent, int flags, int startId)
{
Log.i(TAG, "onStartCommand methode called");
Runnable r = new Runnable() {
@Override
public void run() {
initMqtt();
Log.i(TAG, "start init");
client.setCallback(new MqttCallback() {
@Override
public void connectionLost(Throwable cause) { }
@Override
public void messageArrived(String topic, MqttMessage message) throws Exception
{
Toast.makeText(getApplicationContext(),"MQTT Message:\n" + new String(message.getPayload()), Toast.LENGTH_SHORT).show();
Intent done = new Intent();
done.setAction("mqttData");
String json = new String(message.getPayload());
done.putExtra("newData",json);
LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(done);
}
@Override
public void deliveryComplete(IMqttDeliveryToken token) {
}
});
}
};
Thread backgroundThread = new Thread(r);
backgroundThread.start();
return Service.START_STICKY;
}
//unnecessary code here
}
活动:
public class mainView extends AppCompatActivity {
private ListView datalist;
private CustomAdapter mAdapter;
ArrayList<Datamodel> list;
Gson gson;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_view);
datalist = findViewById(R.id.datalistview);
gson = new Gson();
Intent i = new Intent(this, mqtt_service.class);
startService(i);
list = new ArrayList<>();
list.add(new Datamodel("1", "12", "Number1","Number2", "Test"));
list.add(new Datamodel("2", "20", "Teststring","testtext", "Name"));
mAdapter = new CustomAdapter(this,R.layout.listview_item,list);
datalist.setAdapter(mAdapter);
}
BroadcastReceiver DataReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String neuer = intent.getStringExtra("newData");
Object object = gson.fromJson(neuer,Object.class);
ArrayList<Datamodel> newData = (ArrayList<Datamodel>) object;
list.addAll(newData);
mAdapter.notifyDataSetChanged()
//Update listview here????
}
};
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
LocalBroadcastManager.getInstance(Stoermeldungen_mainView.this).registerReceiver(DataReceiver,new IntentFilter("mqttData"));
}
}
服务中的重要部分是messageArrived方法,从这里我将数据(数据是一个Json字符串)传递给活动。 在活动中,我在BroadcastReceiver中接收数据,并将带有gson的Json字符串转换为原始数据(arraylist。最后,我将新数据添加到我的listview中,这是问题,它没有更新。也许有人可以给我一些指针