android中的handler使用之四

來源:互聯網
上載者:User

標籤:

我們知道handler是android中的一個傳送機制,可以傳送各種各樣的訊息,使得多線程的使用更加方便。但是我這裡說的是,我們還可以利用handler來截斷髮送的訊息。代碼如下

xml代碼

 1 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 2     xmlns:tools="http://schemas.android.com/tools" 3     android:layout_width="match_parent" 4     android:layout_height="match_parent" 5     tools:context="com.example.android_handler2.MainActivity" > 6     <Button  7         android:id="@+id/button" 8         android:layout_width="fill_parent" 9         android:layout_height="wrap_content"10         android:text="@string/button_string"11         />12 </LinearLayout>

java代碼

 1 package com.example.android_handler2; 2  3  4  5  6  7 import android.app.Activity; 8 import android.os.Bundle; 9 import android.os.Handler;10 import android.os.Handler.Callback;11 import android.os.Message;12 import android.view.View;13 import android.view.View.OnClickListener;14 import android.widget.Button;15 import android.widget.Toast;16 17 public class MainActivity extends Activity  implements OnClickListener{18     private Button button = null;19     private Handler handler = new Handler(new Callback() {20         //只要return的是true,就會截斷下面的handlerMessage中接的方法21         public boolean handleMessage(Message msg) {22             Toast.makeText(MainActivity.this, "1", Toast.LENGTH_LONG).show();23             return true;24         }25     }){26         public void handleMessage(Message msg) {27             Toast.makeText(MainActivity.this, "2", Toast.LENGTH_LONG).show();28             return ;29         }30     };31     protected void onCreate(Bundle savedInstanceState) {32         super.onCreate(savedInstanceState);33         setContentView(R.layout.activity_main);34         button = (Button) findViewById(R.id.button);35         button.setOnClickListener(this);36     }37     @Override38     public void onClick(View v) {39         handler.sendEmptyMessage(1);40         41     }42 43 }

運行這個程式我們知道,toast只列印出1,而沒列印出2來,因此表明2已經被截斷了。

android中的handler使用之四

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.