android组件BroadCastReceiver简单使用(一)

 广播接收者作为四大组件之一,可以接收频道发送的广播,发送者可以是Activity,也可以是Service. 它能够监听系统的广播,自己的广播,并作出相应的处理。后台线程执行耗时操作后,可以通过广播接收者将数据返回。

广播分为普通广播和有序广播,
普通广播:一次传递给各个接受者做处理, 过滤信息+传递的内容
发送广播:Context.sendBroadCast

有序广播:可以按照接受者的优先级进行排序,高优先级先接收出来
  发送广播:Context.sendOrderedBroadCast

本文使用普通广播如下:
布局文件很简单,只有一个button

   
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main"
    android:layout_width="match_parent" android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.example.administrator.broadcastreceiver.MainActivity">

    <Button
        android:id="@+id/send"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="发送广播"
        android:onClick="btnClick"
        />

LinearLayout>

接收广播
1,定义一个类,继承BroadCastReceiver
2,重写onReceive(Context context,Intent intent)
3,注册方式分两种
a,动态注册
b,静态注册
在清单文件中
–(全局)

    

    

        

    

    

主页面:



import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    private MyReceiver myReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //静态注册
        myReceiver = new MyReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("dong");//频道需要与发送者一致
        registerReceiver(myReceiver,intentFilter);

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(myReceiver);
    }

    /**
     * 发送广播
     * @param view
     */
    public void btnClick(View view) {
        Intent intent=new Intent();
        intent.setAction("dong");//设置频道
        intent.putExtra("s","haha");
        sendBroadcast(intent);//发送普通广播
    }

    //定义一个类继承BroadCastReceiver 重写onReceive 利用intent获取信息
    class MyReceiver extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {
            String s = intent.getStringExtra("s");
            Toast.makeText(MainActivity.this, s, Toast.LENGTH_SHORT).show();
        }
    }

}

好了,很简单吧!

你可能感兴趣的:(android)