恢弘志士之气,不宜妄自菲薄。这篇文章主要讲述安卓Broadcast Receiver(广播消息)应用实例相关的知识,希望能为你提供帮助。
利用Intent发送广播消息,广播消息的内容可以是应用程序相关的数据信息,也可以是android的系统消息例如:网络连接变化、电池电量变化、接收短信或系统设置变化。
【安卓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>
推荐阅读
- Android Stuido 提高开发效率的插件
- Ionic2 + cordova + angular2 打包Android APP环境搭建
- Android应用程序访问linux驱动第一步(实现并测试Linux驱动)
- apply()与call()的区别
- Android 解决小米手机Android Studio安装app 报错的问题It is possible that this issue is resolved by uninstalling an
- 全面解读商城购物app开发的开发市场现状
- Android Studio 常用快捷键 for mac
- app 安全测试概览
- JavaFX进度指示器