• android学习十三(android的通知使用)


             通知(Notification)是android系统中比較有特色的一个功能,当某个应用程序希望向用户发出一些提示信息。而该应用程序又不在前台执行时,就能够借助通知来实现。发出一条通知后,手机最上方的状态栏会显示一个通知的图标。下拉状态后能够看到通知的具体内容。


    通知的基本使用方法

       通知能够在活动,广播接收器,和服务里面创建。不管在哪里创建通知,总体的步骤都是同样的,以下我们来学习具体的步骤。

    /*
    	 * 首先须要一个NotificationManager来对通知进行管理。能够调用Context的getSystemService()方法
    	 * 获取到。

    getSystemService方法接收一个字符串參数用于确定获取系统的哪个服务,这里我们传入的 * Context.NOTIFICATION_SERVICE就可以。因此获取NotificationManager的实例就能够写成: * NotificationManager manager=(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); * 接下来要创建一个Notification对象,这个对象用于存储通知所需的各种信息,我们使用它的构造函数来进行创建。 * Notification的有參构造函数接收三个參数。第一个參数用于指定通知的图标。比方项目的res/drawable文件夹 * 下有一张ic_launcher图片。那么这里就能够传入R.drawable.ic_launcher,第二个參数用于指定通知 * 的ticker内容,当通知刚被创建的时候,它会在系统的状态栏一闪而过,属于瞬时的提示信息。

    第三个參数用于 * 指定通知被创建的时间。以毫秒为单位。当下拉系统状态栏时,这里指定的时间会显示在对应的通知上。因此创建 * 一个Notification对象就能够写成: * Notification notification=new Notification(R.drawable.ic_launcher, "this is ticker text",System.currentTimeMillis()); * 创建好了Notification对象后。我们还须要对通知的布局进行设定,这里仅仅须要调用Notification的 * setLatestEventInfo()方法就能够给通知设置一个标准布局。

    这种方法接收四个參数。第一个參数 * 是Context。第二个參数用于指定通知的标题内容,下拉系统状态栏就能够看到这部分内容。第三个參数用于指定 * 通知的正文内容,相同下拉系统状态栏就能够看到这部分内容。

    第四个參数我们临时用不到,能够传入null。因此 * 对通知的布局进行设定就能够写成: * notification.setLatestEventInfo(this, "this is content title", "this is content text", null); 以上工作都做完了后,仅仅须要调用NotificationManager的notify()方法就能够让通知显示出来了。 notify()方法接收2个參数,第一个參数是id,要保证为每一个通知所指定的id都是不同的。第二个參数则是 Notification对象。这里直接将我们刚刚创建好的Notification对象传入就可以。因此,显示一个通知就能够 写成: manager.notify(1,notification); * */


    新建一个项目,项目名为NotificationTest。并改动activity_main.xml中的代码,例如以下所看到的:

    <LinearLayout 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"
        android:orientation="vertical"
        >
    
        <Button 
            android:id="@+id/send_notice"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="send notice"
            />
    
    </LinearLayout>
    

    改动MainActivity中的代码:

    package com.jack.notificationtest;
    
    import android.os.Bundle;
    import android.app.Activity;
    import android.app.Notification;
    import android.app.NotificationManager;
    import android.content.Context;
    import android.content.IntentSender.SendIntentException;
    import android.view.Menu;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    
    public class MainActivity extends Activity implements OnClickListener{
    
    	/*
    	 * 首先须要一个NotificationManager来对通知进行管理。能够调用Context的getSystemService()方法
    	 * 获取到。getSystemService方法接收一个字符串參数用于确定获取系统的哪个服务。这里我们传入的
    	 * Context.NOTIFICATION_SERVICE就可以。因此获取NotificationManager的实例就能够写成:
    	 * NotificationManager manager=(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    	 * 接下来要创建一个Notification对象。这个对象用于存储通知所需的各种信息,我们使用它的构造函数来进行创建。
    	 * Notification的有參构造函数接收三个參数。第一个參数用于指定通知的图标。比方项目的res/drawable文件夹
    	 * 下有一张ic_launcher图片,那么这里就能够传入R.drawable.ic_launcher,第二个參数用于指定通知
    	 * 的ticker内容,当通知刚被创建的时候。它会在系统的状态栏一闪而过,属于瞬时的提示信息。

    第三个參数用于 * 指定通知被创建的时间。以毫秒为单位,当下拉系统状态栏时,这里指定的时间会显示在对应的通知上。因此创建 * 一个Notification对象就能够写成: * Notification notification=new Notification(R.drawable.ic_launcher, "this is ticker text",System.currentTimeMillis()); * 创建好了Notification对象后,我们还须要对通知的布局进行设定,这里仅仅须要调用Notification的 * setLatestEventInfo()方法就能够给通知设置一个标准布局。这种方法接收四个參数,第一个參数 * 是Context。

    第二个參数用于指定通知的标题内容。下拉系统状态栏就能够看到这部分内容。第三个參数用于指定 * 通知的正文内容,相同下拉系统状态栏就能够看到这部分内容。第四个參数我们临时用不到,能够传入null。因此 * 对通知的布局进行设定就能够写成: * notification.setLatestEventInfo(this, "this is content title", "this is content text", null); 以上工作都做完了后,仅仅须要调用NotificationManager的notify()方法就能够让通知显示出来了。

    notify()方法接收2个參数,第一个參数是id。要保证为每一个通知所指定的id都是不同的。

    第二个參数则是 Notification对象,这里直接将我们刚刚创建好的Notification对象传入就可以。

    因此,显示一个通知就能够 写成: manager.notify(1,notification); * */ private Button sendNotice; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); sendNotice=(Button) findViewById(R.id.send_notice); sendNotice.setOnClickListener(this); } @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 void onClick(View v) { // TODO Auto-generated method stub switch(v.getId()){ case R.id.send_notice: NotificationManager manager=(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); Notification notification=new Notification(R.drawable.ic_launcher, "this is ticker text",System.currentTimeMillis()); notification.setLatestEventInfo(this, "this is content title", "this is content text", null); manager.notify(1,notification); break; default: break; } } }


    执行程序。点击森达 notice界面例如以下:



    下拉系统状态栏能够看到该通知的具体信息,例如以下所看到的:



         上面的通知。我们不能点击,假设要想实现通知的点击效果,我们就要在代码中进行对应的设置,这涉及到了PendingIntent。PendingIntent和Intent有些类似,它们之间也确实存在在不少共同点。

    比方它们都能够去指明一个“意图”,都能够用于启动活动,启动服务以及发送广播等。不同的是Intent更倾向于立马运行某个动作,而PendingIntent更倾向于在某个合适的时机去运行某个动作。

    所以也能够把PendingIntent简单的理解为延迟运行的Intent。

       PendingIntent的使用方法比較简单。它主要提供了几个静态方法用于获取PendingIntent的实例,能够依据需求来选择是使用getActivity()方法,getBroadcast()方法。还是getService()方法。

    这几个方法所接收的參数都是同样的。第一个參数依然是Context。第二个參数一般用不到,通常传入0就可以。

    第三个參数是一个Intent对象,我们能够通过这个对象构建出PendingIntent的“意图”。

    第四个參数用于确定PendingIntent的行为,有FLAG_ONE_SHOT,FLAG_NO_CREATE,FLAG_CANCEL_CURRENT 和  FLAG_UPDATE_CURRENT这四种值可选,每种值的含义,能够自己查询下。

        还记得Notification的setLatestEventInfo()方法。刚才我们将setLatestEventInfo()的第四个參数忽略掉了,直接传入了null。如今你会发现,第四个參数正是一个PendingIntent对象。

    因此,这里就能够通过PendingIntent构建出一个延迟运行的“意图”,当用户点击这条通知时就会运行对应的逻辑。

        如今我们来优化下NotificationTest项目。给刚才的通知加上点击功能,让用户点击它的时候能够启动还有一个活动。

        首先须要准备好一个活动,这里新建布局文件notification_layout.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" >
        
        <TextView 
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="24sp"
            android:text="this is notificaiton layout"
            />
    
    </LinearLayout>
    


    新建NotificationActivity类继承Activity。载入上面定义的布局,代码例如以下所看到的:

    package com.jack.notificationtest;
    
    import android.app.Activity;
    import android.os.Bundle;
    
    public class NotificationActivity extends Activity {
    
    	@Override
    	protected void onCreate(Bundle savedInstanceState) {
    		// TODO Auto-generated method stub
    		super.onCreate(savedInstanceState);
    		setContentView(R.layout.notification_layout);
    	}
    
    }
    
    改动AndroidManifest.xml中的代码,在里面增加NotificationActivity的注冊声明:

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.jack.notificationtest"
        android:versionCode="1"
        android:versionName="1.0" >
    
        <uses-sdk
            android:minSdkVersion="13"
            android:targetSdkVersion="17" />
    
        <application
            android:allowBackup="true"
            android:icon="@drawable/ic_launcher"
            android:label="@string/app_name"
            android:theme="@style/AppTheme" >
            <activity
                android:name="com.jack.notificationtest.MainActivity"
                android:label="@string/app_name" >
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />
    
                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
            
            <activity 
                android:name="com.jack.notificationtest.NotificationActivity"
                ></activity>
            
            
        </application>
    
    </manifest>
    

    以下在改动MainActivity中的代码给通知增加点击功能,例如以下所看到的:

    @Override
    	public void onClick(View v) {
    		// TODO Auto-generated method stub
    		switch(v.getId()){
    		case R.id.send_notice:
    			NotificationManager manager=(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    			Notification notification=new Notification(R.drawable.ic_launcher,
    					"this is ticker text",System.currentTimeMillis());
    			
    			Intent intent=new Intent(this,NotificationActivity.class);
    			PendingIntent pi=PendingIntent.getActivity(this, 0,
    					intent, PendingIntent.FLAG_CANCEL_CURRENT);
    			
    			notification.setLatestEventInfo(this, "this is content title",
    					"this is content text", pi);
    			manager.notify(1,notification);
    			break;
    		default:
    			break;
    		}
    	}
    


    又一次执行下程序。并点击send noticebutton,依然会发出一条通知。让回下拉系统状态栏,点击下该通知,就会看到NotificationActivity这个活动界面了。例如以下所看到的:





    注意看,你会发现系统状态上面的图标还没有消失。这是为什么了?这是由于,假设我们没有在代码中对该通知进行取消,它会一直在系统的状态栏上显示。解决办法也比較简单的,调用NotificationManager的cancel()方法就能够取消通知了。改动NotificationActivity中的代码,例如以下所看到的:


    package com.jack.notificationtest;
    
    import android.app.Activity;
    import android.app.NotificationManager;
    import android.content.Context;
    import android.os.Bundle;
    
    public class NotificationActivity extends Activity {
    
    	@Override
    	protected void onCreate(Bundle savedInstanceState) {
    		// TODO Auto-generated method stub
    		super.onCreate(savedInstanceState);
    		setContentView(R.layout.notification_layout);
    		NotificationManager manager=(NotificationManager) 
    				getSystemService(Context.NOTIFICATION_SERVICE);
    		manager.cancel(1);
    		/*
    		 * 我们在cancel()方法中传入了1。这个1是什么意思了?这是我们给这条通知设置的id就是1。
    		 * 因此假设,你想要取消哪一条通知。就在cancel()方法中传入该通知的id即可了。
    		 * */
    	}
    
    }
    


    通知的高级技巧

        观察Notification这个类,你会发现我们还有非常多的属性,没有使用。

    先来看看sound这个属性吧。它能够在通知发出的时候播出一段音频,这样就能够更好地告知用户有通知到来。sound这个属性是一个Uri对象,所以在指定音频文件的时候还须要先获取音频文件相应的URI。比方说手机的/system/media/audio/ringtongs文件夹下有一个basic_tone.ogg音频文件,那么在代码中这样就能够这样指定:

    Uri soundUri=Uri.parse(new File("/system/media/audio/ringtongs/basic_tone.ogg"));

    notification.sound=soundUri;

    除同意播放音频以外,我们还能够在通知到来的时候让手机进行震动,使用的是vibrate这个属性。它是一个长整形的数组。因为设置手机精巧和震动的时长,以毫秒为单位。下标0的值表示手机精巧的时长,下标为1的值表示手机震动的时长。下标为2的值又表示手机精巧的时长,以此类推。所以,假设想要手机在通知到来的时候立马震动1秒,然后精巧1秒,在震动,代码就能够写成:

    long[] vibrates={0,1000,1000,1000};

    notification.vibrate=vibrates;


    只是想要控制手机震动还须要声明权限,因此,我们还得编辑AndroidManifest.xml文件。增加例如以下说明:

    <uses-permission android.name="android.permission.VIBRATE"/>


         学会控制通知的声音和震动。以下我们来看看怎样在通知到来的时候控制手机LED灯的显示。

         如今的手机基本上都会前置一个LED灯。当有未接电话或未读短信,而此时手机又处于锁屏状态时LED灯就会不停地闪烁,提醒用户去查看。

    我们能够使用ledARGB,ledOnMS,ledOffMS以及flags这几个属性来实现这样的效果。ledARGB用于控制LED灯的颜色,一般有红绿蓝三种颜色可选。

    ledOnMS用于指定LED灯亮起的时长,以毫秒为单位。edOffMS因为指定LED灯暗去的时长。也是以毫秒为单位。flags可用于指定通知的一些行为,当中就包含显示LED灯这一选项。所以。等通知到来时,假设想要实现LED灯以绿色的灯一闪一闪的效果。就能够写成:

    notification.ledARGB=Color.GREEN;

    notification.ledOnMS=1000;

    notification.ledOffMS=1000;

    notification.flags=Notification.FLAG_SHOW_LIGHTS;

    当然,假设你不想进行那么多繁琐的设置,也能够直接使用通知的默认效果,它会依据当前手机的环境来决定播放什么铃声。以及怎样震动,写法例如以下:

    notification.defaults=Notification.DEFAULT_ALL;

    注意:以上所涉及的这些高级技巧都要在真机上面执行,才干看到效果,模拟器无法表现出震动。以及LED灯闪烁等功能。

    通知就总结到这了额,以下一篇将进行短信的接收与发送总结。

    转载请注明:http://blog.csdn.net/j903829182/article/details/41181277


  • 相关阅读:
    洛谷P2742 【模板】二维凸包
    计算几何笔记
    洛谷P1251 餐巾计划问题(最小费用最大流)
    洛谷P2762 太空飞行计划问题(最大权闭合图)
    洛谷P2764 最小路径覆盖问题(二分图)
    [置顶] Guava学习之ArrayListMultimap
    sphinx coreseek SetSortMode(SPH_SORT_ATTR_ASC, '') 对float 排序设置bug
    magento 修改 paypal order product name
    硬盘“坏了”怎么办
    能够兼容ViewPager的ScrollView
  • 原文地址:https://www.cnblogs.com/yangykaifa/p/6758560.html
Copyright © 2020-2023  润新知