一、使用本地广播发送一条广播(本例为自己发送自己接收,本地广播也可以是其他应用接收)然后接收到广播时回调Receiver类中的回调方法onReceive()在此方法中自定义发出通知
代码
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
效果如下: