安卓Broadcast Receiver(广播消息)应用实例

恢弘志士之气,不宜妄自菲薄。这篇文章主要讲述安卓Broadcast Receiver(广播消息)应用实例相关的知识,希望能为你提供帮助。
  利用Intent发送广播消息,广播消息的内容可以是应用程序相关的数据信息,也可以是android的系统消息例如:网络连接变化、电池电量变化、接收短信或系统设置变化。
【安卓Broadcast Receiver(广播消息)应用实例】  截图:

安卓Broadcast Receiver(广播消息)应用实例

文章图片

 
代码:(主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 { 13Button ob1; 14Intent intent; 15@Override 16protected void onCreate(Bundle savedInstanceState) { 17super.onCreate(savedInstanceState); 18setContentView(R.layout.activity_main); 19 20ob1=(Button) findViewById(R.id.bu1); //按钮 21intent=new Intent("com.example.playmessage"); //设置唯一标识 22ob1.setOnClickListener(new OnClickListener() { 23 24@Override 25public void onClick(View v) { 26// TODO Auto-generated method stub 27sendBroadcast(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 { 10public MyReceiver() { 11} 12MediaPlayer play; 13@Override 14public void onReceive(Context context, Intent intent) { 15// TODO: This method is called when the BroadcastReceiver is receiving 16// an Intent broadcast. 17Toast.makeText(context, "收到广播,播放音乐",2).show(); ; 18play=MediaPlayer.create(context,R.raw.sleep); 19play.start(); 20 21} 22 }

需要在清单文件中Broadcast-Receiver下添加Intent的过滤
< intent-filter>
      < action android:name="   设置的唯一标识 " />
< intent-filter>
 

    推荐阅读