Android之Notification类(浅谈)

1.概述

       在使用手机时,当手机有未接来电,短信,电子邮件,以及其他Application推送的一些消息,这些消息通常会显示在状态栏上,android也提供 了用于处理这些信息的类----Notification&NotificationManager。Notification表示一个持久的通 知,将提交给用户使用NotificationManager,用户使用NotificationManager来发送Notification通知的系 统务。             

      Notification是一种让你的应用程序在没有开启情况下或在后台运行警示用户用的。eg,  BroadCast Receiver/Service/等一些看不见的Activity;

       使用Notification&NotificationManager发送通知,大概分为以下四个步骤。

        (1).调用getSystemService()方法获取系统的NotificationManager服务;

private NotificationManager notificationManager; //定义通知管理器的对象
notificationManager=(NotificationManager)getSystemService(NOTIFICATION_SERVICE);

        (2).创建一个Notification对象,并为其设置各种属性;

// 定义Notification的各种属性
int icon = R.drawable.icon; //通知图标
CharSequence tickerText = "Hello"; //状态栏显示的通知文本提示
long when = System.currentTimeMillis(); //通知产生的时间,会在通知信息里显示
//用上面的属性初始化 Nofification
Notification notification = new Notification(icon,tickerText,when);
/*也可以分开设置
Notification notification = new Notification();
notify.icon=imageId[which];
notify.tickerText=title[which];
notify.when=System.currentTimeMillis();
*/
/*
* 添加声音
* notification.defaults |=Notification.DEFAULT_SOUND;
* 或者使用以下几种方式
* notification.sound = Uri.parse("file:///sdcard/notification/ringer.mp3");
* notification.sound = Uri.withAppendedPath(Audio.Media.INTERNAL_CONTENT_URI, "6");
* 如果想要让声音持续重复直到用户对通知做出反应,则可以在notification的flags字段增加"FLAG_INSISTENT"
* 如果notification的defaults字段包括了"DEFAULT_SOUND"属性,则这个属性将覆盖sound字段中定义的声音
*/
/*
* 添加振动
* notification.defaults |= Notification.DEFAULT_VIBRATE;
* 或者可以定义自己的振动模式:
* long[] vibrate = {0,100,200,300}; //0毫秒后开始振动,振动100毫秒后停止,再过200毫秒后再次振动300毫秒
* notification.vibrate = vibrate;
* long数组可以定义成想要的任何长度
* 如果notification的defaults字段包括了"DEFAULT_VIBRATE",则这个属性将覆盖vibrate字段中定义的振动
*/
/*
* 添加LED灯提醒
* notification.defaults |= Notification.DEFAULT_LIGHTS;
* 或者可以自己的LED提醒模式:
* notification.ledARGB = 0xff00ff00;
* notification.ledOnMS = 300; //亮的时间
* notification.ledOffMS = 1000; //灭的时间
* notification.flags |= Notification.FLAG_SHOW_LIGHTS;
*/
/*
* 更多的特征属性
* notification.flags |= FLAG_AUTO_CANCEL; //在通知栏上点击此通知后自动清除此通知
* notification.flags |= FLAG_INSISTENT; //重复发出声音,直到用户响应此通知
* notification.flags |= FLAG_ONGOING_EVENT; //将此通知放到通知栏的"Ongoing"即"正在运行"组中
* notification.flags |= FLAG_NO_CLEAR; //表明在点击了通知栏中的"清除通知"后,此通知不清除,
* //经常与FLAG_ONGOING_EVENT一起使用
* notification.number = 1; //number字段表示此通知代表的当前事件数量,它将覆盖在状态栏图标的顶部
* //如果要使用此字段,必须从1开始
* notification.iconLevel = ; //
*/

        (3)为Notification对象设置事件信息

//设置通知的事件消息
Context context = getApplicationContext(); //上下文
CharSequence contentTitle = "My Notification"; //通知栏标题
CharSequence contentText = "Hello World!"; //通知栏内容
Intent notificationIntent = new Intent(this,Main.class); //点击该通知后要跳转的Activity
PendingIntent contentIntent = PendingIntent.getActivity(this,0,notificationIntent,0);
notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
/*通过一个方法设置事件信息
notify.setLatestEventInfo(MainActivity.this, user, title[which], null);

      (4)通过NotificationManager类的notify(int id,Notification notification)方法发送Notification通知

notificationManager.notify(NOTIFYID_1,notify);

2.实例 手机登录转态显示

Activity_main.xml布局文件如下(登录界面)

<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/tableLayout1"
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent"
    android:gravity="center_vertical"
    android:stretchColumns="0,3"
    
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.eg_loginstatus.MainActivity" >

    <!-- 第一行 -->
    <TableRow android:id="@+id/tableRow1" 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
        <TextView/>
        <TextView android:text="用户名:" 
            android:id="@+id/textView1" 
            android:layout_width="wrap_content"
            android:textSize="24px" 
            android:layout_height="wrap_content"
            />
        <EditText android:id="@+id/user" 
            android:textSize="24px" 
            android:layout_width="wrap_content" 
            android:layout_height="wrap_content" android:minWidth="200px"/>
        <TextView />
    </TableRow>
    <!-- 第二行 -->    
    <TableRow android:id="@+id/tableRow2" 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
        <TextView/>
        <TextView android:text="密    码:" 
            android:id="@+id/textView2" 
            android:textSize="24px" 
            android:layout_width="wrap_content" 
            android:layout_height="wrap_content"/>
        <EditText android:layout_height="wrap_content" 
            android:layout_width="wrap_content" 
            android:textSize="24px" 
            android:id="@+id/pwd" 
            android:inputType="textPassword"/>
        <TextView />
    </TableRow>
    <!-- 第3行 -->
    <TableRow android:id="@+id/tableRow3" 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
        <TextView/>
        <Button android:text="登录" 
            android:id="@+id/login" 
            android:layout_width="wrap_content" 
            android:layout_height="wrap_content"/>
        <Button android:text="退出" 
            android:id="@+id/quit" 
            android:layout_width="wrap_content" 
            android:layout_height="wrap_content"/>
        <TextView />
    </TableRow>
</TableLayout>

创建布局列表项items.xml,采用LinearLayout布局,添加TextView和ImageView组件,分别用于显示列表项中的图标和文字。代码如下:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="horizontal"
  android:layout_width="match_parent"
  android:layout_height="match_parent">
<ImageView 
    android:id="@+id/image" 
    android:paddingLeft="10px"
    android:paddingTop="20px"
    android:paddingBottom="20px"
    android:adjustViewBounds="true"
    android:maxWidth="72px"
    android:maxHeight="72px"
    android:layout_height="wrap_content" 
    android:layout_width="wrap_content"/>  
 <TextView  
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:padding="10px"
    android:layout_gravity="center"
    android:id="@+id/title"
    />     
</LinearLayout>

Java全部代码如下:

package com.example.eg_loginstatus;

import android.support.v7.app.ActionBarActivity;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.app.AlertDialog;
import android.app.Notification;
import android.content.DialogInterface;
import android.app.NotificationManager;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.SimpleAdapter;
import android.widget.TableRow;

public class MainActivity extends ActionBarActivity {

    final int NOTIFYID_1=123;  //第一个通知的ID
    private String user="匿名";   //用户名
    private NotificationManager notificationManager; //定义通知管理器的对象
    
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //获取通知管理器
        notificationManager=(NotificationManager)getSystemService(NOTIFICATION_SERVICE);
        //获取登录按钮
        Button login=(Button)findViewById(R.id.login);
        //为登录按钮设置监听器
        login.setOnClickListener(new OnClickListener() {
            
            @Override
            public void onClick(View view) {
                // TODO Auto-generated method stub
                EditText edusr=(EditText)findViewById(R.id.user);
                if(!"".equals(edusr.getText())){
                    user=edusr.getText().toString();
                    
                }
                MainActivity.this.sendNotification();
            }
        });
        
        Button quit=(Button)findViewById(R.id.quit);
        quit.setOnClickListener(new OnClickListener() {
            
            @Override
            public void onClick(View view) {
                // TODO Auto-generated method stub
                notificationManager.cancel(NOTIFYID_1);
                ((TableRow)findViewById(R.id.tableRow1)).setVisibility(View.VISIBLE);
                ((TableRow)findViewById(R.id.tableRow2)).setVisibility(View.VISIBLE);
                ((Button)findViewById(R.id.login)).setText("登录");
                
            }
        });
        
    }

    /**
     * 发送通知方法
     */
    private void sendNotification(){
        android.app.AlertDialog.Builder builder=new AlertDialog.Builder(MainActivity.this);
        builder.setIcon(R.drawable.advise);
        builder.setTitle("我的登录状态");
        final int imageId[]=new int[]{
            R.drawable.img1,R.drawable.img2,R.drawable.img3,R.drawable.img4    
        };
        final String title[]=new String[]{
            "在线","隐身","忙碌","离线"
        };
        List<Map<String,Object>> listitems=new ArrayList<Map<String,Object>>();
        //通过for循环将图片id和列表项文字放到Map中,并添加到list集合中
        for(int i=0;i<imageId.length;i++){
            Map<String, Object> map=new HashMap<String, Object>();
            map.put("image", imageId[i]);
            map.put("title", title[i]);
            listitems.add(map);
        }
        final SimpleAdapter adapter=new SimpleAdapter(MainActivity.this, listitems,
                               R.layout.items, new String[]{"title","image"},new int[]{R.id.title,R.id.image});
        builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
            
            @SuppressWarnings("deprecation")
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub
                Notification notify=new Notification();
                notify.icon=imageId[which];
                notify.tickerText=title[which];
                notify.when=System.currentTimeMillis();
                notify.defaults=Notification.DEFAULT_SOUND;
                notify.setLatestEventInfo(MainActivity.this, user, title[which], null);
                notificationManager.notify(NOTIFYID_1,notify);
                //设置布局中的第一行不显示
                ((TableRow)findViewById(R.id.tableRow1)).setVisibility(View.INVISIBLE);
                //设置布局中的第二行不显示
                ((TableRow)findViewById(R.id.tableRow2)).setVisibility(View.INVISIBLE);
                ((Button)findViewById(R.id.login)).setText("更改登录状态");
            }
        });
        builder.create().show();
        
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}









转载于:https://my.oschina.net/caipeng/blog/525379

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值