android基础学习之广播

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

发送广播的代码,其实我觉得就两个东西,一个是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 {

	@Override
	public void onReceive(Context context, Intent intent) {
		String type=intent.getAction();
		//get the type of the broad
		if(type.equals("jike.test")){
			//get the bundle from the intent
			Bundle b=intent.getExtras();
			//get the data from the bundle
			String 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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值