Android状态栏通知Status Bar Notification

Android状态栏通知Status Bar Notification

状态栏通知最典型的一种就是当收到短信时会在状态栏上显示一个通知,可
以用鼠标点击状态栏并向下拖动,以查看是否有新的状态栏通知。

文章来源:好岸园it技术网 http://www.hopean.com

strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">ANotificationDemo</string>
    <string name="hello_world">Hello world!</string>
    <string name="menu_settings">Settings</string>
	<string name="send">发送通知</string>
</resources>


main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <Button
		android:layout_width="wrap_content"
		android:layout_height="wrap_content"
		android:text="@string/send"
		android:id="@+id/button"
		/>

</RelativeLayout>


java代码如下

MainActivity.java

package com.example.anotificationdemo;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.view.Menu;

public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		Button button = (Button)findViewById(R.id.button);
		button.setOnClickListener(new View.OnClickListener() {
		@SuppressWarnings("deprecation")
		@Override
		public void onClick(View v) {
		//获取通知管理器
		NotificationManager mNotificationManager = (NotificationManager)
		getSystemService(Context.NOTIFICATION_SERVICE);
		int icon = android.R.drawable.sym_action_email;
		long when = System.currentTimeMillis();
		//新建一个通知,指定其图标和标题
		//第一个参数为图标,第二个参数为标题,第三个为通知时间
		@SuppressWarnings("deprecation")
		Notification notification = new Notification(icon, null, when);
		notification.defaults = Notification.DEFAULT_SOUND;//发出默认声音
		//当点击消息时就会向系统发送 openintent 意图
		PendingIntent contentIntent = PendingIntent.getActivity(MainActivity.this, 0, null, 0);
		notification.setLatestEventInfo(MainActivity.this, "通知", "今天下午 5 点全体人员到会议室开会!", contentIntent);
		mNotificationManager.notify(0, notification);//发送通知
		}
		});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

}


修改完成后就能运行出所要的结果了

源码下载:ANotificationDemo

欢迎光临小站 好岸园 http://www.hopean.com
原文地址:https://www.cnblogs.com/hopeanCom/p/2845426.html