0

大家好,圣诞快乐。

请看这段代码。

如您所见,有一个从服务接收消息的处理程序。

当 Activty 被销毁时,我负责销毁 Service,但似乎 Service 仍在向 Handler 发送回消息(我不认为是这种情况)。

由于某种原因,处理程序似乎还活着并发布:

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

就像它继续接收消息一样。

谢谢你的帮助!!!

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);         
    }

这是服务:

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;
    }


}

我在 onDestroy() 中关闭了主 Activity 上的服务:

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

2 回答 2

2

由于此无限循环,您将继续从您的服务接收消息

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);

            }
        }
}

无条件 for 循环正在执行无限过程,因此您的服务线程仍在向您发送消息,对吗?

只需放入!isCancelled()您的循环,您现在就可以停止您的循环并Asynctask

for (int in = 0; !isCancelled() ; in++) { 
    // ...
}
于 2012-12-24T12:20:17.557 回答
1

请看这个。这不是你的问题的答案。它会帮助你得到答案,

如何停止处理程序?

于 2012-12-24T11:49:04.963 回答