标签:bundle mes 过滤 标识 view raw player height rate
利用Intent发送广播消息,广播消息的内容可以是应用程序相关的数据信息,也可以是Android的系统消息例如:网络连接变化、电池电量变化、接收短信或系统设置变化。
截图:
代码:(主Activity)
1 package com.example.playmessage; 2 3 import android.app.Activity; 4 import android.content.Intent; 5 import android.os.Bundle; 6 import android.view.Menu; 7 import android.view.MenuItem; 8 import android.view.View; 9 import android.view.View.OnClickListener; 10 import android.widget.Button; 11 12 public class MainActivity extends Activity { 13 Button ob1; 14 Intent intent; 15 @Override 16 protected void onCreate(Bundle savedInstanceState) { 17 super.onCreate(savedInstanceState); 18 setContentView(R.layout.activity_main); 19 20 ob1=(Button) findViewById(R.id.bu1); //按钮 21 intent=new Intent("com.example.playmessage"); //设置唯一标识 22 ob1.setOnClickListener(new OnClickListener() { 23 24 @Override 25 public void onClick(View v) { 26 // TODO Auto-generated method stub 27 sendBroadcast(intent); //发送广播 28 29 } 30 }); 31 32 33 } 34 35 36 }
Broadcast-Receiver
1 package com.example.playmessage; 2 3 import android.content.BroadcastReceiver; 4 import android.content.Context; 5 import android.content.Intent; 6 import android.media.MediaPlayer; 7 import android.widget.Toast; 8 9 public class MyReceiver extends BroadcastReceiver { 10 public MyReceiver() { 11 } 12 MediaPlayer play; 13 @Override 14 public void onReceive(Context context, Intent intent) { 15 // TODO: This method is called when the BroadcastReceiver is receiving 16 // an Intent broadcast. 17 Toast.makeText(context, "收到广播,播放音乐",2).show();; 18 play=MediaPlayer.create(context,R.raw.sleep); 19 play.start(); 20 21 } 22 }
需要在清单文件中Broadcast-Receiver下添加Intent的过滤
<intent-filter>
<action android:name=" 设置的唯一标识 " />
<intent-filter>
安卓Broadcast Receiver(广播消息)应用实例
标签:bundle mes 过滤 标识 view raw player height rate
原文地址:http://www.cnblogs.com/llsq/p/7710087.html