LocalBroadcastManager 的使用
生活随笔
收集整理的這篇文章主要介紹了
LocalBroadcastManager 的使用
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
一、使用本地廣播發送一條廣播(本例為自己發送自己接收,本地廣播也可以是其他應用接收)然后接收到廣播時回調Receiver類中的回調方法onReceive()在此方法中自定義發出通知
代碼
1 package com.qf.broadcastreceiver06; 2 3 import android.app.Activity; 4 import android.app.Notification; 5 import android.app.NotificationManager; 6 import android.content.BroadcastReceiver; 7 import android.content.Context; 8 import android.content.Intent; 9 import android.content.IntentFilter; 10 import android.graphics.BitmapFactory; 11 import android.os.Bundle; 12 import android.support.v4.app.NotificationCompat; 13 import android.support.v4.content.LocalBroadcastManager; 14 import android.view.View; 15 16 public class MainActivity extends Activity { 17 18 LocalBroadcastManager localBroadcastMgr;//本地廣播管理器 19 20 MyReceiver myReceiver; 21 @Override 22 protected void onCreate(Bundle savedInstanceState) { 23 super.onCreate(savedInstanceState); 24 setContentView(R.layout.activity_main); 25 26 //獲取本地廣播管理器對象 27 localBroadcastMgr=LocalBroadcastManager.getInstance(getApplicationContext()); 28 29 myReceiver=new MyReceiver(); 30 //注冊本地廣播接收器 31 localBroadcastMgr.registerReceiver(myReceiver, new IntentFilter("com.qf.broadcast.disen")); 32 } 33 34 public void sendBroadcast(View v){//發送本地廣播 35 36 Intent intent=new Intent("com.qf.broadcast.disen"); 37 38 //通過本地廣播管理器來發送廣播 39 localBroadcastMgr.sendBroadcast(intent); 40 } 41 42 43 @Override 44 protected void onDestroy() { 45 super.onDestroy(); 46 47 //取消注冊本地廣播接收器 48 localBroadcastMgr.unregisterReceiver(myReceiver); 49 } 50 51 //定義廣播接收器 52 class MyReceiver extends BroadcastReceiver{ 53 @Override 54 public void onReceive(Context context, Intent intent) { 55 // TODO Auto-generated method stub 56 //發送通知 57 58 //獲取系統的通知管理器組件 59 NotificationManager notifyMgr= 60 (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE); 61 62 //實例化廣播構造器 63 NotificationCompat.Builder builder= 64 new NotificationCompat.Builder(getApplicationContext()); 65 66 //設置通知的小圖標、標題、內容、滾動內容、動作等 67 builder.setSmallIcon(android.R.drawable.ic_menu_call) 68 .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher)) 69 .setContentTitle("提示") 70 .setContentText("最新消息:暫定今天下午5點開會,請準時回來.....") 71 //設置通知在狀態欄里滾動 72 .setTicker("最新消息:暫定今天下午5點開會,請準時回來.....最新消息:暫定今天下午5點開會,請準時回來.....最新消息:暫定今天下午5點開會,請準時回來.....") 73 .setPriority(NotificationCompat.PRIORITY_MAX) 74 .setDefaults(Notification.DEFAULT_SOUND); 75 76 notifyMgr.notify(1, builder.build()); 77 78 } 79 } 80 } MainActivity.java效果如下:
轉載于:https://www.cnblogs.com/bimingcong/p/4820434.html
總結
以上是生活随笔為你收集整理的LocalBroadcastManager 的使用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 算法图解--python
- 下一篇: Ubuntu文件压缩、解压缩、打包