Notify the current Activity that background function has finished running Android

0


I have a class that looks for a list of clients in the background with a AsyncTask . It can be called from any Activity , and returns nothing, just fetches the list of clients that comes in json and saves that list as string to SharedPreferences .
Initially, I am ordering to get the list on my login screen, so when I bring the user data from the database, it already has to fetch the list of clients (to reduce waiting for data search), but I I needed that when that class saved the list in SharedPreferences my Activity that is opened after login was notified so I fill a RecyclerView with it. I thought of Implementing a Interface in AsyncTask but it returns to the Activity that called it.
Is there a method that notifies Activity even though the function has not been started by it?

Note: If you have not understood the question, comment before you deny that I will be happy to answer your questions.

    
asked by anonymous 11.07.2016 / 17:02

1 answer

1

Good afternoon,

You can do what you want in a number of ways, for a simpler solution I use a BroadCastReceiver but if you are going to use it in several classes, it might be better to create an interface for it.

Here is an example of Braodcast:

Activity

BroadCastReceiver myReceiver;
 protected void onCreate(Bundle savedInstanceState) {

 IntentFilter filter = new IntentFilter();

            filter.addAction("lista.atualizada");

            myReceiver = new BroadcastReceiver() {  //  < ------ Declare o Bradcast como global

                @Override
                public void onReceive(Context context, Intent intent) {
                   // Atualize o que quiser, foi atualizado

                }
            };
            registerReceiver(myReceiver, filter);

}


 @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(myReceiver); // <---- não esqueça de destruir o receiver junto com a activity
    }

Then in your task :

Intent atualizouLista = new Intent();

atualizouLista.setAction("lista.atualizada"); // < ---- aqui é o nome da sua "ação" a mesma que você registrou no receiver
mContext.sendBroadcast(atualizouLista); // < --- repare que estou passando mContext, na sua Task você precisa manter uma referência do seu contexto.
    
11.07.2016 / 21:32