I continue to receive messages after Activity is destroyed

Hi everybody and Merry Christmas.

Please see this snippet of code.

As you can see there is an Handler that receives messages form a Service.

When the Activty is destroyed, I take care of destroying the Service, nevertheless it seems like the Service is still sending back messages to the Handler (which I don't think it is the case).

For some reason the Handler seems to stay alive and post:

 Log.e("","MESSAGGIO RICEVUTO");

like it is continuing to receive messages.

Thanks for your help!!!

private String url;
    private String url2;
private WebView browser;
private HttpClient client;
private List<Forecast> forecasts=new ArrayList<Forecast>();
public String responseBody;
    public ArrayList<Stock> lt;
    public LocalService mService;
    boolean mBound = false;
    public MyAdapter myAdap;
    public Messenger messenger;
    public Grab g;
    public Handler handler;
    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.main);
        url2=getString(R.string.url2);
        Log.e("", "arrivo a prima di forecast");
        g = new Grab(url2);
        String s = g.vai();
        Log.e("", s);
        Log.e("", "passo oltre l'invocazione al grab");
        lt = new MyParser(s).parseResp();
        ListView lv = (ListView)findViewById(android.R.id.list);
        myAdap= new MyAdapter(lt, this); 
        lv.setAdapter(myAdap);
        lv.setOnItemClickListener(new myListener());

        handler=new Handler() {
            @Override
            public void handleMessage(Message msg) {
            Log.e("","MESSAGGIO RICEVUTO");
            lt = mService.ritira();
            myAdap.notifyDataSetChanged();
            g.fermaGrab();
            }
            };
        messenger = new Messenger(handler);         
    }

This is the Service:

public class LocalService extends Service {
    public Messenger messenger;
public int i;
   public ArrayList<Stock> al;
    public DefaultHttpClient client;
// Binder given to clients
    private final IBinder mBinder = new LocalBinder();
    public Task t;

    /**
     * Class used for the client Binder.  Because we know this service always
     * runs in the same process as its clients, we don't need to deal with IPC.
     */
    public class LocalBinder extends Binder {
        LocalService getService() {
            // Return this instance of LocalService so clients can call public methods
            return LocalService.this;
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        Log.e("", "sono nel service");      
        messenger = (Messenger) intent.getExtras().get("messenger");
        return mBinder;
    }  

    class Task extends AsyncTask<Void, String, Void> {
        @Override
        protected Void doInBackground(Void... unused) {     
        Log.e("Sono nel AsyncTask del Service", Integer.toBinaryString(i));
 /////////INIZIA IL CASINO
        client=new DefaultHttpClient();
        for(int in=0;;in++)
        {       
        for(int i=0;i<al.size();i++)
        {
            String srt="";
            String url     =getString(R.string.dettaglio1).concat("'"+al.get(i).simbolo+"'").concat(getString(R.string.    dettaglio2));

            HttpGet getMethod=new HttpGet(url);

            try {
                ResponseHandler<String> responseHandler=new BasicResponseHandler();
                srt=client.execute(getMethod, responseHandler);
                //Log.e("", "passo per GrabXML");
                int inizio = srt.indexOf("<company data=\"");
                int fine = srt.indexOf("\"/>",inizio+15);
                String s =srt.substring(inizio+15,fine).substring(0, 10);

                al.get(i).setNome(s);
                Log.e("",al.get(i).nome);
                //Log.e("",Integer.toString((al.get(i).nome.length())));

                inizio = srt.indexOf("<last data=\"");
                fine = srt.indexOf("\"/>",inizio+12);
                al.get(i).setPrezzo(srt.substring(inizio+12,fine));
                //Log.e("",Float.toString(al.get(i).prezzo));

                inizio = srt.indexOf("<perc_change data=\"");
                fine = srt.indexOf("\"/>",inizio+19);
                al.get(i).setCambiamento(srt.substring(inizio+19,fine));
                //Log.e("",Float.toString(al.get(i).cambiamento));
            }
            catch (Throwable t) {
                android.util.Log.e("grabXML", "Exception fetching data", t);
                    }           
            }
/////////INIZIA IL CASINO
        Collections.sort(al, new Comparator<Stock>(){
              public int compare(Stock s1, Stock s2) {
                return s1.nome.compareToIgnoreCase(s2.nome);
              }
            });         

        Message msg=Message.obtain();

        try {
            messenger.send(msg);
        } catch (RemoteException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        SystemClock.sleep(6000);

        }
        /////////FINISCE IL CASINO      

        }

        @Override
        protected void onProgressUpdate(String... unused) {
            }

        @Override
        protected void onPostExecute(Void unused) {     
            }

    }



    public void stop() {
        Log.e("", "passo per lo stop del Service");
        t.cancel(true);
        client.getConnectionManager().shutdown();
        return;
    }


}

I shut down the Service on the main Activity in the onDestroy():

 protected void onDestroy() {
    Log.e("ondestroy","passo per ondestroy"); 
    //handler.removeMessages();
    mService.stop();
    g.fermaGrab();
    handler.removeMessages(333); 
    //g=null;
    super.onDestroy();   
    }

Answers


You're continuing receiving a message from your service because of this infinite loop

class Task extends AsyncTask<Void, String, Void> {
        @Override
        protected Void doInBackground(Void... unused) {  
            for (int in = 0;; in++) { 
               // .. Other definition

               Message msg = Message.obtain();

               try {
               messenger.send(msg);
               } catch (RemoteException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
               }
               SystemClock.sleep(6000);

            }
        }
}

A conditionless for-loop is doing an infinite process, so your service's thread is still sending you a message right?

Just put !isCancelled() in your loop, and you can now stop your loop and Asynctask

for (int in = 0; !isCancelled() ; in++) { 
    // ...
}

Need Your Help

How to use onclick event for a button generated through a template?

javascript jquery underscore.js

Testing underscore.js. Using its templating engine. Problem is, I am unable to use the on-click listener, written with jquery.AJAX when the button is drawn from within the template. Here the code:

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.