LocalBroadcastManager 的使用
2015-09-18 21:49
239 查看
一、使用本地广播发送一条广播(本例为自己发送自己接收,本地广播也可以是其他应用接收)然后接收到广播时回调Receiver类中的回调方法onReceive()在此方法中自定义发出通知
代码
MainActivity.java
效果如下:
代码
package com.qf.broadcastreceiver06; import android.app.Activity; import android.app.Notification; import android.app.NotificationManager; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.graphics.BitmapFactory; import android.os.Bundle; import android.support.v4.app.NotificationCompat; import android.support.v4.content.LocalBroadcastManager; import android.view.View; public class MainActivity extends Activity { LocalBroadcastManager localBroadcastMgr;//本地广播管理器 MyReceiver myReceiver; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //获取本地广播管理器对象 localBroadcastMgr=LocalBroadcastManager.getInstance(getApplicationContext()); myReceiver=new MyReceiver(); //注册本地广播接收器 localBroadcastMgr.registerReceiver(myReceiver, new IntentFilter("com.qf.broadcast.disen")); } public void sendBroadcast(View v){//发送本地广播 Intent intent=new Intent("com.qf.broadcast.disen"); //通过本地广播管理器来发送广播 localBroadcastMgr.sendBroadcast(intent); } @Override protected void onDestroy() { super.onDestroy(); //取消注册本地广播接收器 localBroadcastMgr.unregisterReceiver(myReceiver); } //定义广播接收器 class MyReceiver extends BroadcastReceiver{ @Override public void onReceive(Context context, Intent intent) { // TODO Auto-generated method stub //发送通知 //获取系统的通知管理器组件 NotificationManager notifyMgr= (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE); //实例化广播构造器 NotificationCompat.Builder builder= new NotificationCompat.Builder(getApplicationContext()); //设置通知的小图标、标题、内容、滚动内容、动作等 builder.setSmallIcon(android.R.drawable.ic_menu_call) .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher)) .setContentTitle("提示") .setContentText("最新消息:暂定今天下午5点开会,请准时回来.....") //设置通知在状态栏里滚动 .setTicker("最新消息:暂定今天下午5点开会,请准时回来.....最新消息:暂定今天下午5点开会,请准时回来.....最新消息:暂定今天下午5点开会,请准时回来.....") .setPriority(NotificationCompat.PRIORITY_MAX) .setDefaults(Notification.DEFAULT_SOUND); notifyMgr.notify(1, builder.build()); } } }
MainActivity.java
效果如下:
相关文章推荐
- 枚举法 4 —— 《实用算法基础教程》
- UI_UIStepper
- Summary Ranges
- socket 异步选择 WSAAsyncSelect 用法
- PHP版本中的VC6,VC9,VC11,TS,NTS区别
- 数组类型——typedef定义的数组类型的函数调用
- 1.9-samba 部署和优化-3
- MTK 时间 时区问题解决方案
- 京东2015在线笔试 (2)
- UI控件以及视图控制器执行时的几种常使用到的方法
- POJ 3294 出现在至少K个字符串中的子串
- 计算2的N次方&&计算e
- 京东2015在线笔试 (2)
- 时间DateTime类型转换为字符串String格式方法汇总
- 京东校招编程题——小熊分苹果
- 【leetcode】No.81 Search in Rotated Sorted Array II
- Android基本控件
- 黑马程序员-Java基础学习-正则表达式
- NSDictionary writeToFile:atomically: 时失败
- 算法之每日一题:棋盘寻宝扩展