对应Android消息通知栏应用的这样的效果是很常见的,它使用了Android4大组件中的broadcast receiver这个组件,这里我使用的方法是新建的一个类继承与BroadcastReceiver
要实现这种效果我总结了这几个步骤:
1、创建一个类继承于Broadcastreceiver类
2、在这个类中必须创建NotificationManager和Notification类
3、在AndroidManifest.xml中配置<receiver>节点
实现后的效果图为:
总体的步骤我分为这几步,具体代码实现如下:
NotificationReceiver.java类继承于BroadcastReceiver
package com.tenghu.json.activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class NotificationReceiver extends BroadcastReceiver{
//声明NotificationManager和Notification对象
public static NotificationManager notificationManager;
private Notification notification;
//创建通知ID,这个ID是通知栏中的唯一ID,清除通知栏时就可以使用该ID
public static final int NOTIFICATION_ID=1;
@Override
public void onReceive(Context context, Intent intent) {
sendNotification(context);
}
/**
* 自定义一个方法来发送通知
*/
private void sendNotification(Context context){
//创建Intent对象,用于用户点击通知栏时进入制定的Activity中
Intent intent=new Intent(context,MainActivity.class);
//设置一个Activity模式,这里用于当用户点击跳转后,原来的程序自动退出
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//创建PendingIntent对象
PendingIntent contentIntent=PendingIntent.getActivity(context, 0, intent, 0);
//创建通知内容
CharSequence contentTitle="My notification";
CharSequence contentText="Hello Word!!!";
//创建Notification对象
this.notification=new Notification();
//设置消息图标
notification.icon=R.drawable.ic_launcher;
//设置消息信息
notification.tickerText="Hello";
//设置当前时间
notification.when=System.currentTimeMillis();
//将通知内容与contentItent设置到Notification中
notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
//获取NotificationManager
notificationManager=(NotificationManager) context.getSystemService("notification");
//将Notification传送到NotificationManager中
notificationManager.notify(NOTIFICATION_ID, notification);
}
}
配置AndroidManifest.xml文件
<receiver android:name="com.tenghu.json.activity.NotificationReceiver" android:exported="false">
<intent-filter >
<action android:name="com.tenghu.json.action.NotificationReceiver"/>
</intent-filter>
</receiver>
布局文件配置
<Button
android:id="@+id/btn_send"
android:onClick="send"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/edit_border"
android:text="发送"
/>
在主程序中调用这个类
public void send(View view){
Intent intent=new Intent();
intent.setAction("com.tenghu.json.action.NotificationReceiver");
//这里调用的<intent-filter>节点下的<action>中配置的android:name属性,就是通过它去调用继承与broadcaseReceiver的那一个类
sendBroadcast(intent);
}
下面这个方法的作用是,当程序退出时,通知栏上的消息也跟着清除
@Override
protected void onDestroy() {
NotificationReceiver.notificationManager.cancel(NotificationReceiver.NOTIFICATION_ID);
//这里是调用NotificationManager管理类的cancel方法,将在上面NotificationReceiver.java类中创建的NOTIFICATION_ID传入, super.onDestroy();
}
具体实现与代码全部在这里,说错的地方还请多多指教,因为我也是第一次学Android