android基础学习之广播

来源:互联网 发布:手机频率对讲机软件 编辑:程序博客网 时间:2024/05/23 10:38

都说广播是个很重要的东西,今天学了一下广播,就简单的贴出广播的收发,以及一些我认为需要注意的地方吧。

发送广播的代码,其实我觉得就两个东西,一个是sendbroacast,需要的是intent,然后就是需要为intent设置一个action参数,为了得到一个统一的type

package com.jk.send;import android.os.Bundle;import android.app.Activity;import android.content.Intent;import android.view.Menu;public class MainActivity extends Activity {    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        //declarand and initalize a intent        Intent intent=new Intent();        //set a acton for the intent just for get the same tag        intent.setAction("jike.test");        //declar and initalize a bundle for transfor the data        Bundle b=new Bundle();        //put the data        b.putString("key","ni hao");        //put the bundle        intent.putExtras(b);        //send the broadcast        sendBroadcast(intent);    }        }

接受广播,这个我个人认为就是继承了BroadCastReceiver,然后重写里面的onReveive方法,可以通过里面的intent参数获得广播的类型,代码如下

package com.jk.bro;import android.content.BroadcastReceiver;import android.content.Context;import android.content.Intent;import android.os.Bundle;import android.widget.Toast;public class onReceive extends BroadcastReceiver {@Overridepublic void onReceive(Context context, Intent intent) {String type=intent.getAction();//get the type of the broadif(type.equals("jike.test")){//get the bundle from the intentBundle b=intent.getExtras();//get the data from the bundleString s=b.getString("key");Toast.makeText(context, s, Toast.LENGTH_LONG).show();}}}

接下来就是配置xml文件了,首先是receiver里面的属性,如果不是在同一个程序之中,我们需要写全包名,然后intentfilter里面的actionname里面,我们需要写的就是我们统一的那个类型了,最后就是手机首发短信的权限了,代码。。。

 <receiver android:name="com.jk.bro.onReceive">            <intent-filter><action android:name="jike.test"/>                            </intent-filter>        </receiver>    </application><uses-permission android:name="android.permission.SEND_SMS"/>


0 0
原创粉丝点击