broadcast初级:发送broadcast,注册receiver,创建IntentFilter

(一)通过配置xml文件:

发送broadcast:

findViewById(R.id.button1).setOnClickListener(new OnClickListener()
{
    @Override
    public void onClick(View v)
    {
        Intent intent = new Intent();
        intent.setAction("com.example.aex13_broadcast.sendone");
        sendBroadcast(intent);
    }
});


配置清单:添加intent-filter

<receiver
            android:name="com.example.aex13_broadcast.MyReceiver"
            android:enabled="true"
            android:exported="true" >
            <intent-filter >
                <action android:name="com.example.aex13_broadcast.sendone"/>
            </intent-filter>
        </receiver>

接收系统广播:

1.短信: name="android.provider.Telephony.SMS_RECEIVED"



(二)通过代码设置

public class MainActivity extends Activity
{
    BroadcastReceiver receiver = new MyReceiver();//创建接收者对象
    @Override
    protected void onStart()
    {
        super.onStart();
        IntentFilter filter = new IntentFilter();//创建IntentFilter
        filter.addAction("com.example.aex15_codereceive.codereceive");
        registerReceiver(receiver, filter);//注册接收者
    }
                 
    @Override
    protected void onStop()
    {
        super.onStop();
        unregisterReceiver(receiver);//注销接收者
    }
                 
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
                     
        findViewById(R.id.button1).setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                Intent intent = new Intent();
                intent.setAction("com.example.aex15_codereceive.codereceive");
                sendBroadcast(intent);//发送广播
            }
        });
                 
    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
}










本文出自 “天空没有痕迹但我飞过” 博客,转载请与作者联系!

你可能感兴趣的:(Broadcast,IntentFilter,receiver,sendBroadcas)