状态栏获取信息

效果图


主界面代码

package com.xiaoke.notification;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RemoteViews;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;

public class MainActivity extends Activity {

	private final int NOTIFICATION_ID = 105;

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

		Button send = (Button) findViewById(R.id.send);
		send.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				sendNotification();
			}
		});

		Button clear = (Button) findViewById(R.id.clear);
		clear.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				clearNotification();
			}
		});
	}

	private void sendNotification() {
		// 获取管理工具

		NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		// 获取管理工具中的通知工具
		NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
				this);
		// 设置通知栏样式
		mBuilder.setSmallIcon(R.drawable.dev);

		// 系统下拉弹出自带样式
		// mBuilder.setContentTitle("通知的标题");
		// mBuilder.setContentText("通知的内容");

		Notification notification = mBuilder.build();

		// 找到自定义布局文件
		RemoteViews rv = new RemoteViews(getPackageName(), R.layout.a_text);
		// 设置布局文件的内容
		// rv.setImageViewResource(R.id.image, R.drawable.edn);
		// rv.setTextViewText(R.id.title, "来消息啦");
		// rv.setTextViewText(R.id.text, "还不来看我");
		// 添加进标题栏
		notification.contentView = rv;

		// 缺省设置为当发送通知到通知栏时候:提示声音 + 手机震动
		notification.defaults = Notification.DEFAULT_SOUND
				| Notification.DEFAULT_VIBRATE;

		// 要注意的是,作为选项,此处可以设置MainActivity的启动模式为singleTop,避免重复新建onCreate()。
		// 通知的时间
		notification.when = System.currentTimeMillis();
		// 找到要跳转的布局文件
		Intent intent = new Intent(this, MainActivity.class);
		PendingIntent pi = PendingIntent.getActivity(this, 0x05, intent,
				PendingIntent.FLAG_UPDATE_CURRENT);
		// 添加进标题栏中,点击开始跳转
		notification.contentIntent = pi;
		
		 // 点击notification自动消失  
        notification.flags = Notification.FLAG_AUTO_CANCEL;

		// 发送到手机的通
		notificationManager.notify(NOTIFICATION_ID, notification);
	}

	// 清除消息
	private void clearNotification() {
		NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		notificationManager.cancel(NOTIFICATION_ID);
	}
}

主界面UI代码
  
  
    
通知显示代码




    

        

            

            

            

            

            
        

        

            

            

            

            

            
        
    



你可能感兴趣的:(android)