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


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. 參考



免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM