[Android] Service和IntentService中顯示Toast的區別

來源:互聯網
上載者:User
1. 表象
    Service中可以正常顯示Toast,IntentService中不能正常顯示Toast,在2.3系統上,不顯示toast,在4.3系統上,toast顯示,但是不會消失。
2. 原因
    Toast要求運行在UI主線程中。    Service運行在主線程中,因此Toast是正常的。    IntentService運行在獨立的線程中,因此Toast不正常。
3. 在IntentService中顯示Toast
    利用Handler,將顯示Toast的工作,放在主線程中來做。具體有兩個實現方式。
    Handler的post方式實現,這個方式比較簡單。
    private void showToastByRunnable(final IntentService context, final CharSequence text, final int duration)     {        Handler handler = new Handler(Looper.getMainLooper());        handler.post(new Runnable() {            @Override            public void run() {                Toast.makeText(context, text, duration).show();            }        });    }


    Handler的msg方式實現,這個方式比較複雜。

    Handler msgHandler = new Handler(Looper.getMainLooper()) {        @Override        public void handleMessage(Message msg) {            Toast.makeText(ToastIntentService.this, msg.getData().getString("Text"), Toast.LENGTH_SHORT).show();            super.handleMessage(msg);        }    };    private void showToastByMsg(final IntentService context, final CharSequence text, final int duration) {        Bundle data = new Bundle();        data.putString("Text", text.toString());        Message msg = new Message();        msg.setData(data);        msgHandler.sendMessage(msg);    }

4. 關於耗時操作        Service中如果有耗時的操作,要開啟一個Thread來做。    IntentService是在獨立的線程中,所以可以進行一些耗時操作。
5.  考慮AsyncTask與Service的使用區別        如果是全背景工作,使用Service,結果的提示可以使用Notification。    如果是非同步工作,工作結束後需要更新UI,那麼最好使用Thread或者AsyncTask。
6. 參考
   
Android Handler機制詳解   

http://developer.android.com/reference/android/os/Handler.html    深入理解ANDROID訊息處理系統——LOOPER、HANDLER、THREAD7. 本文地址      http://blog.csdn.net/xiaodongrush/article/details/9628849

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.