广播机制

一、             广播机制

广播类:

public class MyReveiver extends BroadcastReceiver {

//等待接收广播

    @Override

    public void onReceive(Context context, Intent intent) {

       // TODO Auto-generated method stub

       String str=intent.getStringExtra("gb");

       Toast.makeText(context, str, Toast.LENGTH_LONG).show();

    }

 

}

Activity类:

//发送一个广播  

Intent intent=new Intent();

    intent.setAction(Intent.ACTION_EDIT);

    intent.putExtra("gb", "hi,我收到了消息!");

    BroadcastDemo.this.sendBroadcast(intent);

Manifest代码清单:

<receiverandroid:name=".MyReveiver">

       <intent-filter>

       <actionandroid:name="android.intent.action.EDIT"/>

       </intent-filter>

       </receiver>

二、             广播机制

使用代码注册广播:

广播类:

public class SmsReceiver extends BroadcastReceiver {

 

    @Override

    public void onReceive(Context context, Intent intent) {

       // TODO Auto-generated method stub

       

       Bundle bundle=intent.getExtras();

       Object[] objs=(Object[])bundle.get("pdus");

       SmsMessage[] msgs=new SmsMessage[objs.length];

       for(int i=0;i<msgs.length;i++){

           msgs[i]=SmsMessage.createFromPdu((byte[])objs[i]);

           String str=msgs[i].getDisplayMessageBody();

           //System.out.println(new String(str.getBytes("unicode"),"gbk"));

           Toast.makeText(context,str , Toast.LENGTH_LONG).show();

       }

       

       

    }

 

}

Activity类代码:

class Btn1 implements OnClickListener{

//注册广播,并声明通过类型

       public void onClick(View v) {

           // TODO Auto-generated method stub

           rece=new SmsReceiver();

           IntentFilter filter=new IntentFilter();

           filter.addAction("android.provider.Telephony.SMS_RECEIVED");

           BroadcastDemo2.this.registerReceiver(rece, filter);

       }

    

    }

    class Btn2 implements OnClickListener{

    public void onClick(View v) {

//取消注册

           // TODO Auto-generated method stub

           BroadcastDemo2.this.unregisterReceiver(rece);

       }

    }

 

 

 

posted @ 2011-08-29 23:02  rorshach  阅读(142)  评论(0编辑  收藏  举报