Broadcast的动态注册与静态注册和Notification的使用

一、    实现内容

二、实验基本

广播的详细过程
 发送广播:在需要发送信息的地方,把要发送的信息和用于过滤的信息(如Action、Category)装入一个Intent对象,调用Context.sendBroadcast() 方法把Intent对象以广播方式发送出去。
 接收广播:当Intent发送以后,所有已经注册的BroadcastReceiver会检查注册时的IntentFilter是否与发送的Intent相匹配,若匹配则就会调用BroadcastReceiver的void onReceive(Context curContext, Intent broadcastMsg)方法。

注册BroadcastReceiver

有两种方式:一种方式是,静态的在AndroidManifest.xml中用<receiver>标签生命注册,并在标签内用<intent- filter>标签设置过滤器。

另一种方式是,动态的在代码中先定义并设置好一个 IntentFilter 对象,然后在需要注册的地方调Context.registerReceiver()方法,如果取消时就调用 Context.unregisterReceiver()方法。如果用动态方式注册的BroadcastReceiver的Context对象被销毁时,BroadcastReceiver也就自动取消注册了。(特别注意,有些可能需要后台监听的,如短信消息)

另外,若在使用sendBroadcast()的方法是指定了接收权限,则只有在AndroidManifest.xml中用<uses- permission>标签声明了拥有此权限的BroascastReceiver才会有可能接收到发送来的Broadcast。同样,若在注册BroadcastReceiver时指定了可接收的Broadcast的权限,则只有在包内的AndroidManifest.xml中 用<uses-permission>标签声明了,拥有此权限的Context对象所发送的Broadcast才能被这个 BroadcastReceiver所接收

 

BroadcastReceiver开发过程如下
1. 开发BroadcastReceiver子类,重写onReceive()
2. 注册BroadcastReceiver对象
3. 将要广播的消息封装到Intent中,调用方法发送出去
4. 通过IntentFilter对象过滤Intent,处理信息名称匹配的广播

Notification可以提供持久的通知,位于手机最上层的状态通知栏中。用手指按下状态栏,并从手机上方向下滑动,就可以打开状态栏查看提示消息。开发Notification
主要涉及以下3个类:
1. Notification.Builder:用于动态的设置Notification的一些属性。
2. NotificationManager:负责将Notification在状态显示出来和取消;
3. Notification:设置Notification的相关属性。

 

三、代码

MainActivity.Java

package com.example.hp.lab4;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

final Button static_button=(Button)findViewById(R.id.static_button);
final Button dynamic_button=(Button)findViewById(R.id.dynamic_button);

static_button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, StaticActivity.class);
startActivity(intent);
}
});
dynamic_button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, DynamicActivity.class);
startActivity(intent);
}
});
}
}

StaticActivity.Java

package com.example.hp.lab4;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import java.util.ArrayList;
import java.util.List;

/**
* Created by HP on 2016/10/14.
*/
public class StaticActivity extends Activity {

private List<Fruit> fruit_list =new ArrayList<Fruit>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.static_layout);


final ListView list_id=(ListView) findViewById(R.id.listview);
initFruit();
final FruitAdapter fruitAdapter=new FruitAdapter(this,fruit_list);
list_id.setAdapter(fruitAdapter);

list_id.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent=new Intent("com.example.lab4.staticreceiver");
intent.putExtra("id",fruit_list.get(position).getResourceId());
intent.putExtra("name",fruit_list.get(position).getName());
sendBroadcast(intent);
}
});



}

void initFruit(){
fruit_list.add(new Fruit(R.mipmap.apple,"Apple"));
fruit_list.add(new Fruit(R.mipmap.banana,"Banana"));
fruit_list.add(new Fruit( R.mipmap.cherry,"Cherry"));
fruit_list.add(new Fruit(R.mipmap.coco,"Coco"));
fruit_list.add(new Fruit( R.mipmap.kiwi,"Kiwi"));
fruit_list.add(new Fruit( R.mipmap.orange,"Orange"));
fruit_list.add(new Fruit(R.mipmap.pear,"Pear"));
fruit_list.add(new Fruit( R.mipmap.strawberry,"Strawberry"));
fruit_list.add(new Fruit( R.mipmap.watermelon,"Watermelon"));
}
}

StaticReceiver.java

package com.example.hp.lab4;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;

import java.util.Random;

/**
* Created by HP on 2016/10/14.
*/
public class StaticReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
Bundle bundle=intent.getExtras();
//由Icon的id得到Bitmap
Bitmap bitmap= BitmapFactory.decodeResource(context.getResources(),bundle.getInt("id"));
//通过getSystemService()方法得到NotificationManager对象,它负责管理发送通知、清除通知等一系列的对通知的管理工作。
NotificationManager notificationManager=(NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification.Builder builder=new Notification.Builder(context);
builder.setContentTitle("静态广播")//设置通知栏标题
.setContentText(bundle.getString("name"))//设置通知栏显示内容
.setLargeIcon(bitmap)//通知栏的大Icon
.setTicker("您有一条新信息.")//通知首次出现在通知栏,带上升动画效果
.setSmallIcon(bundle.getInt("id"))
.setAutoCancel(true);//用户点击面板就让通知自动取消
Intent intent2 = new Intent(context, MainActivity.class);//点击时跳转的intent,跳转到MainActivity
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, intent2, 0);//PendingIntent授予启动Mainactivity的权利。
builder.setContentIntent(contentIntent);
Notification notify=builder.build();//绑定通知,
notificationManager.notify(0,notify);//显示通知
}
}

FruitAdapter.java

package com.example.hp.lab4;

import android.content.Context;
import android.media.Image;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.List;

/**
* Created by HP on 2016/10/14.
*/
public class Fruit {
private int resourceId;
private String name;

public Fruit(int resourceId,String name ){
this.resourceId=resourceId;
this.name=name;
}
public String getName(){
return name;
}

public int getResourceId(){
return resourceId;
}

}


public class FruitAdapter extends BaseAdapter {

private Context context;
private List<Fruit> listItem;

public FruitAdapter(Context context,List<Fruit> listItem){
this.context=context;
this.listItem=listItem;
}

@Override
public int getCount(){
if(listItem==null){
return 0;
}
return listItem.size();
}
//获得某个数据
@Override
public Fruit getItem(int i){
if(listItem==null){
return null;
}
return listItem.get(i);
}
//获得数据项的位置
@Override
public long getItemId(int i){
return i;
}

@Override

//获得数据项的布局样式,最重要的一个方法
public View getView(int i, View view, ViewGroup viewGroup){
if(view==null){
//通过inflate的方法加载布局,
view= LayoutInflater.from(context).inflate(R.layout.item,null);
}
//得到单项布局中textview的id
ImageView fruit_image=(ImageView) view.findViewById(R.id.fruit_image);
TextView fruit_name=(TextView) view.findViewById(R.id.fruit_name);

//从数据列表中取出对应的数据并赋值给对应的textview
fruit_image.setImageResource(listItem.get(i).getResourceId());
fruit_name.setText(listItem.get(i).getName());
return view;
}


}

DynamicActivity.java

package com.example.hp.lab4;

import android.app.Activity;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

/**
* Created by HP on 2016/10/14.
*/
public class DynamicActivity extends Activity {

private boolean isRegistered = false;

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dynamic_layout);
final Button register=(Button)findViewById(R.id.register);
final Button send=(Button)findViewById(R.id.send);
final EditText editText=(EditText) findViewById(R.id.edittext);
final DynamicReceiver dynamicReceiver=new DynamicReceiver();
register.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(DynamicActivity.this.isRegistered){
register.setText("Register Broadcast");//设置register按键的内容
unregisterReceiver(dynamicReceiver);//注销广播
DynamicActivity.this.isRegistered=false;
}
else{
register.setText("Unregister Broadcast");
//注册广播,以及广播的action
registerReceiver(dynamicReceiver,new IntentFilter("com.example.lab4.dynamicreceiver"));
DynamicActivity.this.isRegistered=true;

}
}
});
send.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(isRegistered){
Intent intent=new Intent("com.example.lab4.dynamicreceiver");
Bundle bundle=new Bundle();
bundle.putString("message",editText.getText().toString());
intent.putExtras(bundle);
DynamicActivity.this.sendBroadcast(intent);
}

}
});
}
}

DynamicReciver.java

package com.example.hp.lab4;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Icon;
import android.os.Bundle;

import java.io.InputStream;

/**
* Created by HP on 2016/10/14.
*/
public class DynamicReceiver extends BroadcastReceiver{
private static final String DYNAMICACTION="com.example.lab4.dynamicreceiver";//约定俗成,包名+intent.action+MyReceiver
@Override
public void onReceive(Context context, Intent intent){
if(intent.getAction().equals(DYNAMICACTION)){//对Action进行判断
Bitmap bitmap= BitmapFactory.decodeResource(context.getResources(),R.mipmap.dynamic);
Bundle bundle=intent.getExtras();
NotificationManager notificationManager=(NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification.Builder builder=new Notification.Builder(context);
builder.setContentTitle("动态广播")
.setContentText(bundle.getString("message"))
.setLargeIcon(bitmap)
.setTicker("您有一条新信息.")
.setSmallIcon(R.mipmap.dynamic)
.setAutoCancel(false);
Intent intent2 = new Intent(context, MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, intent2, 0);
builder.setContentIntent(contentIntent);
Notification notify=builder.build();
notificationManager.notify(0,notify);
}
}
}

 

项目仓库:https://github.com/luqx3/Broadcast

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 



posted @ 2016-10-18 16:05  sloth_ccc  阅读(935)  评论(0编辑  收藏  举报