Question

I am building an app which requires a connection to an MQTT server. Everything works fine, but I want to make it fail proof. More specifically, I need that when the service is unable to connect to the MQTT server, the application closes as it can't do anything. I tried to broadcast an intent to the activity, but the broadcast doesn't reach it after catching the exception. (I ommited some code for easier understanding)

Service's onHandleIntent()

try{
    mqttClient.connect();
} catch (MqttException e) {
    Intent msgint = new Intent();
    msgint.setAction(constantStrings.SH_CONN_ERROR);
    sendBroadcast(msgint);
    Log.d("MqttLog","ERROR-MqttException " + e.getMessage());
}

The Activity I need to finish (SelectionGrid.class)

@Override
protected void onCreate(Bundle savedInstanceState) {
    [...]
    IntentFilter filter = new IntentFilter();
    filter.addAction(constantStrings.SH_CONNERROR);
    registerReceiver(SH_Communication, filter);
}

BroadcastReceiver SH_Communication = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if(action.equals(constantStrings.SH_CONN_ERROR)){
            new AlertDialog.Builder(getApplicationContext())
            .setTitle("Error")
            .setMessage("No conection")
            .setCancelable(false)
            .setPositiveButton("Close app", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) { 
                    SelectionGrid.this.finish();
                }
             })
            .setIcon(android.R.drawable.ic_dialog_alert)
            .show();
        }
    }
};

I do get the Log entry when catching the exception, but the broadcast never gets to the activity. Is there any better way to do this?

Was it helpful?

Solution

I was able to solve it. It turned out that I was calling the wrong activity which looks a lot like the one I really needed. The code that I showed in the question is correct.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top