Open Alertdialog in current Activity for an already finished android

Asked

Viewed 38 times

0

I’m making a game, in the app as soon as it loses connection to the internet it has to open a Alertdialog in the current Activity, but I’m not getting. alertDialog opens only on the Activity from which onReceive started, in my case Mainactivity.

My codes:

Mainactivity

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        IntentFilter intentFilter = new IntentFilter("android.net.conn.CONNECTIVITY_CHANGE");
        connectivityChangeReceiver = new ConnectivityChangeReceiver();
        registerReceiver(connectivityChangeReceiver, intentFilter);
        ...

Manifest

...
<receiver android:name=".ConnectivityChangeReceiver">
            <intent-filter>
                <action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
            </intent-filter>
        </receiver>
...

Class checking the connection


public class ConnectivityChangeReceiver extends BroadcastReceiver {

    public AlertDialog alerta;

    @Override
    public void onReceive(Context ctx, Intent intent) {
        if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
            if(isConnected(ctx)){
                //O código aqui é executado ao conectar
                Toast.makeText(ctx, "Conectado", Toast.LENGTH_SHORT).show();
                if(alerta!=null){
                    alerta.dismiss();
                }
            }else{
                //O código aqui é executado ao desconectar
                Toast.makeText(ctx, "Desconectado", Toast.LENGTH_SHORT).show();

                LayoutInflater li = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

                View viewCorpo = li.inflate(R.layout.alerta, null);
                View viewTitulo = li.inflate(R.layout.titlealert, null);

                viewCorpo.findViewById(R.id.bt).setOnClickListener(new View.OnClickListener() {
                    public void onClick(View arg0) {
                        alerta.dismiss();
                    }
                });

                AlertDialog.Builder builder = new AlertDialog.Builder(ctx);
                builder.setCustomTitle(viewTitulo);
                builder.setView(viewCorpo);
                builder.setCancelable(false);
                alerta = builder.create();
                alerta.show();
            }
        }
    }

    private boolean isConnected(Context context) {
        ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

        NetworkInfo[] info = connectivity.getAllNetworkInfo();
        if (info != null) {
            for (int i = 0; i < info.length; i++) {
                if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                    return true;
                }
            }
        }
        return false;
    }

As long as the application does not finish() in Mainactiviy, Alertdialog is opened in it, even if the application is already in another finish() run in Mainactivity and the app try to give the show() in Alert the app is closed, I find it very strange because Toast always appears in the current Activity and works perfectly being that Alert uses the same Context as it.

1 answer

0


Create an Activity base to put the Receive code on it, then you will inherit it from it in all your Activity.

Basectivity

  public class BaseActivity extends Activity {

      protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_main);

          IntentFilter intentFilter = new 
          IntentFilter("android.net.conn.CONNECTIVITY_CHANGE");
          connectivityChangeReceiver = new ConnectivityChangeReceiver();
          registerReceiver(connectivityChangeReceiver, intentFilter);
           ...

Outras Activities:

public class Activity extends BaseActivity {
  • It worked in parts. Alertdialog is opening on the current screen, regardless of what, but after I leave Main and enter again it error on show() saying that Activity has been closed. In Basectivity I put extends Appcompatactivity because I use Fragments in the app, it influences something ? I need something in Manifest ?

  • You probably forgot to unregister the broadcast receiver when Activity is destroyed, unregisterReceiver(Broadcastreceiver receiver), you need to respect Lifecycle when updating the view.

  • 1

    It worked perfectly! Thanks a lot for the help. unregisterReceiver(BroadcastReceiver receiver) us onStop()and registerReceiver(BroadcastReceiver receiver,Intent filter) us onStart() of Activity, thus respecting the Lifecycle of the application.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.