国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 系統 > Android > 正文

Android廣播入門,單個手機上App之間的發送接收

2019-11-09 17:35:37
字體:
來源:轉載
供稿:網友

在這里給大家分享安卓四大組件之一Broadcastreceiver(廣播)的學習,在這里今天做一個同一部手機上APP之間的廣播發送和接收.

首先第一個App用于發送廣播出去給其余的App,布局采用一個文本域和一個button按鈕,當我點擊按鈕時進行發送,代碼如下:

    <EditText        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:hint="請輸入問候的語句"        android:id="@+id/main_text_edit"/>    <Button        android:layout_width="wrap_content"        android:layout_gravity="center"        android:layout_height="wrap_content"        android:text="發送"        android:onClick="send"        />當我點擊發送的時候調用當前布局Activity的send方法進行廣播的發送,代碼如下:
    PRivate Intent intent;    private EditText main_text_edit;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        //獲取文本域控件        main_text_edit = (EditText) findViewById(R.id.main_text_edit);        //實力化        intent = new Intent();        //給Intent設置一個特定的廣播名字(專業術語是給Activity設置一個行為);        intent.setAction("com.example.android_broadcastreceiver.01");    }    public void send(View view){        //獲取文本域控件的值        String data=main_text_edit.getText().toString();        //使用Intent攜帶        intent.putExtra("data",data);        //發送廣播        sendBroadcast(intent);    }那么發送廣播就是這樣,現在來寫一個接收廣播的App,由于寫一個簡單點的接收App布局和MainActivity都是創建的那樣不做改動,只是增加一個類繼承BroadcastReceiver類,然后重寫它的一個onReceive方法,這個方法就是接收廣播,代碼如下:

 public void onReceive(Context context, Intent intent) {        if("com.example.android_broadcastreceiver.01".equals(intent.getAction())){            String data=intent.getStringExtra("data");            Log.i("text",data);        }    }在這里的判斷中字符串的值是在第一個發送廣播App中Intent行為的值也就是廣播的名字,當你名字等于我接收廣播的名字時那么就會進入判斷。

在這里要注意一下Android清單文件中要增加幾行代碼,如下:

 <receiver android:name=".MyReceiver">        <intent-filter>            <action android:name="com.example.android_broadcastreceiver.01"></action>        </intent-filter>    </receiver>這代碼加在application標簽中,android:name=我們自己定義繼承BroadcastReceiver的類名。

今天分享的廣播就是這樣了,注意只能在同部手機上App之間的廣播傳遞。


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 沂南县| 南城县| 义乌市| 城固县| 化德县| 南阳市| 靖远县| 莆田市| 莎车县| 呼伦贝尔市| 轮台县| 斗六市| 郸城县| 涪陵区| 洛扎县| 甘德县| 通州市| 鄂州市| 都江堰市| 曲阜市| 咸丰县| 乌兰县| 濮阳县| 当雄县| 博湖县| 永吉县| 大邑县| 同仁县| 县级市| 那曲县| 渝中区| 新郑市| 师宗县| 措勤县| 漯河市| 五峰| 镇赉县| 开封县| 蒙阴县| 牟定县| 宜兰县|