界面很简单:
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
style="@style/all" >
<Button
style="@style/all"
android:onClick="onclick"
android:text="通知" />
<Button
style="@style/all"
android:onClick="onclick2"
android:text="自定义通知" />
</LinearLayout>
content.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="@drawable/ic_launcher" />
</LinearLayout>
以下是主体的代码:
MainActivity.java
package com.example.notification;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.RemoteViews;
import android.widget.RemoteViews.RemoteView;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onclick(View v) {
// 1.得到通知管理器
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// 2.构建通知
Notification noti = new Notification(
android.R.drawable.stat_notify_chat, "这是提示消息 ",
System.currentTimeMillis());
// 3.设置通知栏点击事件
Intent itent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 100,
itent, 0);
noti.setLatestEventInfo(this, "通知的标题", "通知的内容", pendingIntent);
noti.flags = Notification.FLAG_AUTO_CANCEL;// 点击后自动消失
// 4.发送通知
notificationManager.notify(100, noti);
}
public void onclick2(View v) {
// 1.得到通知管理器
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// 2.构建通知
Notification noti = new Notification();
noti.tickerText = "拦截到了N条信息";
noti.icon = R.drawable.ic_launcher;
RemoteViews conteView = new RemoteViews(getPackageName(),R.layout.content);
noti.contentView = conteView;//通知显示的布局
Intent itent = new Intent(this, OtherActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 100,
itent, 0);
noti.contentIntent = pendingIntent;//点击事件
noti.flags = Notification.FLAG_AUTO_CANCEL;// 点击后自动消失
// 4.发送通知
notificationManager.notify(100, noti);
}
}
OtherActivity.java
package com.example.notification;
import android.app.Activity;
import android.os.Bundle;
public class OtherActivity extends Activity{
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content);
}
}