android应用开发学习笔记-BroadcastReceiver

来源:互联网 发布:硕鼠mac youtube 编辑:程序博客网 时间:2024/06/06 06:38

android应用开发学习笔记-BroadcastReceiver

最近对android四大组件之一的Broadcast Receiver进行了简单学习,下面结合demo对该组件的基本用法做小结如下:

/*发送demo*/// MainActivity.javapackage com.example.rlight.broadcastsender;import android.app.Activity;import android.content.Intent;import android.os.Bundle;import android.view.View;import android.widget.Button;public class MainActivity extends Activity {    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        Button mBtnSender = (Button)findViewById(R.id.btn_sender);        mBtnSender.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                //自定义action                String actionStr = "MY_BROADCAST";                Intent intent = new Intent();                intent.setAction(actionStr);                //发送广播                sendBroadcast(intent);            }        });    }}
/*接收demo.接受到所注册广播后,弹toast并启动另外一个activity。*/// MyBroadCastReceiver.javapackage com.example.rlight.broadcasttest;import android.content.BroadcastReceiver;import android.content.Context;import android.content.Intent;import android.widget.Toast;public class MyBroadCastReceiver extends BroadcastReceiver {    @Override    public void onReceive(Context context, Intent intent) {        Toast.makeText(context,"get msg from broadcast!",Toast.LENGTH_LONG).show();        Intent myIntent = new Intent(context,MyMainActivity.class);        myIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);        context.startActivity(myIntent);    }}// MyMainActivity.javapackage com.example.rlight.broadcasttest;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;public class MyMainActivity extends AppCompatActivity {    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_my_main);    }}// AndroidManifest.xml<receiver android:name=".MyBroadCastReceiver">            <intent-filter android:priority="50">                <action android:name="MY_BROADCAST"/>            </intent-filter></receiver>

注意:调用context.startActivity时需要新开一个Task,即先调用addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
在Activity中调用startActivity()时不用addFlags,原因参见Activity.java中相关实现,如下:

/**     * Launch a new activity.  You will not receive any information about when     * the activity exits.  This implementation overrides the base version,     * providing information about     * the activity performing the launch.  Because of this additional     * information, the {@link Intent#FLAG_ACTIVITY_NEW_TASK} launch flag is not     * required; if not specified, the new activity will be added to the     * task of the caller.     *     * <p>This method throws {@link android.content.ActivityNotFoundException}     * if there was no Activity found to run the given Intent.     *     * @param intent The intent to start.     * @param options Additional options for how the Activity should be started.     * See {@link android.content.Context#startActivity(Intent, Bundle)     * Context.startActivity(Intent, Bundle)} for more details.     *     * @throws android.content.ActivityNotFoundException     *     * @see {@link #startActivity(Intent)}     * @see #startActivityForResult     */    @Override    public void startActivity(Intent intent, @Nullable Bundle options) {        if (options != null) {            startActivityForResult(intent, -1, options);        } else {            // Note we want to go through this call for compatibility with            // applications that may have overridden the method.            startActivityForResult(intent, -1);        }    }

更多细节分析可以参考链接:
http://blog.csdn.net/luoshengyang/article/details/6703247

优先级及广播劫持:

通过对优先级的设置,可以实现对sendOrderedBroadcast广播方式所发广播的劫持,实例如下:

//MyBroadcastReceiver2.javapackage com.example.rlight.mybroadcastreceiver2;import android.content.BroadcastReceiver;import android.content.Context;import android.content.Intent;import android.widget.Toast;/** * 描述 * * @author xxx * @date 2016/9/18 */public class MyBroadcastReceiver2 extends BroadcastReceiver {    @Override    public void onReceive(Context context, Intent intent) {        Toast.makeText(context,"[MyBroadcastReceiver2] get msg from broadcast!",Toast.LENGTH_SHORT).show();        abortBroadcast();    }}// AndroidManifest.xml<receiver android:name=".MyBroadcastReceiver2">            <intent-filter android:priority="100">                <action android:name="MY_BROADCAST">                </action>            </intent-filter>        </receiver>

更详细总结可参考:http://www.cnblogs.com/lwbqqyumidi/p/4168017.html
下面以拦截短信为例:

//  AndroidManifest.xml <receiver android:name=".MyBroadcastReceiver2">            <intent-filter android:priority="1000">                <action android:name="MY_BROADCAST">                </action>            </intent-filter>            <intent-filter android:priority="1000">                <action android:name="android.provider.Telephony.SMS_RECEIVED">                </action>            </intent-filter>        </receiver>    </application>    <uses-permission android:name="android.permission.SEND_SMS"></uses-permission>    <uses-permission android:name="android.permission.RECEIVE_SMS"></uses-permission>    <uses-permission android:name="android.permission.READ_SMS"></uses-permission>

在4.4及后续版本不支持通过abortBroadcast实现短信拦截:http://blog.csdn.net/l173864930/article/details/17019615

0 0