技术开发 频道

Android使用Toast和Notification代码

  【IT168技术】之前我们介绍了Android开发之:Toast和Notification概述部分,在本节的内容中,将通过一个具体实例的实现过程,来讲解联合使用Toast和Notification实现提醒功能效果的具体使用流程。本实例源代码保存在“光盘:\daima\6\toast_ and_notification”,具体实现流程如下。

  第1步:打开eclipse,依次单击“File”→“New”→“Android Project”,新建一个名为“toast_and_notification”的工程文件。

  第2步:编写main.xml主文件,此文件是一个布局文件,具体代码如下所示。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation
="vertical" android:layout_width="fill_parent"
    android:layout_height
="fill_parent">
    
<Button android:id="@+id/button1"
        android:layout_width
="wrap_content"
        android:layout_height
="wrap_content" android:text="介绍Notification" />
    
<Button android:id="@+id/button2"
        android:layout_width
="wrap_content"
        android:layout_height
="wrap_content" android:text="介绍Toast" />
</LinearLayout>

  通过上述代码插入了两个Button按钮,执行后效果如图6-63所示。

Android使用Toast和Notification代码
▲图6-63 插入两个Button

  第3步:编写处理文件ActivityMain.java,具体代码如下所示。

package com.eoeandroid.toast_and_notification;
import com.eoeandroid.toast_and_notification.R;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class ActivityMain extends Activity {
    OnClickListener listener1
= null;
    OnClickListener listener2
= null;

    Button button1;
    Button button2;
    @Override
    
public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        listener1
= new OnClickListener() {
            
public void onClick(View v) {
                setTitle(
"介绍Notification");
                Intent intent
= new Intent(ActivityMain.this,
                        ActivityMainNotification.class);
                startActivity(intent);
            }
        };
        listener2
= new OnClickListener() {
            
public void onClick(View v) {
                setTitle(
"介绍Toast");
                Intent intent
= new Intent(ActivityMain.this,
                        ActivityToast.class);
                startActivity(intent);
            }
        };
        setContentView(R.layout.main);
        button1
= (Button) findViewById(R.id.button1);
        button1.setOnClickListener(listener1);
        button2
= (Button) findViewById(R.id.button2);
        button2.setOnClickListener(listener2);
    }
}

  在上述代码中,对两个Button绑定了单击监听器OnClickListener,当单击这两个Button时,会跳转到新的Activity上面。

  第4步:编写第一个Button的处理程序,即单击图6-64中的“介绍Notification”按钮后,执行ActivityMainNotification.java,其主要代码如下所示。

package com.eoeandroid.toast_and_notification;
import com.eoeandroid.toast_and_notification.R;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class ActivityMainNotification extends Activity {
    
private static int NOTIFICATIONS_ID = R.layout.activity_notification;
    
private NotificationManager mNotificationManager;
    @Override
    
public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_notification);
        Button button;
        mNotificationManager
= (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

        button
= (Button) findViewById(R.id.sun_1);
        button.setOnClickListener(
new Button.OnClickListener() {
            
public void onClick(View v) {
                setWeather(
"适合户外", "天气状况", "适合户外", R.drawable.sun);
            }
        });

        button
= (Button) findViewById(R.id.cloudy_1);
        button.setOnClickListener(
new Button.OnClickListener() {
            
public void onClick(View v) {
                setWeather(
"不太适合", "天气状况", "不太适合", R.drawable.cloudy);
            }
        });

        button
= (Button) findViewById(R.id.rain_1);
        button.setOnClickListener(
new Button.OnClickListener() {
            
public void onClick(View v) {
                setWeather(
"不适合", "天气状况", "不适合", R.drawable.rain);
            }
        });

        button
= (Button) findViewById(R.id.defaultSound);
        button.setOnClickListener(
new Button.OnClickListener() {
            
public void onClick(View v) {
                setDefault(Notification.DEFAULT_SOUND);
            }
        });

        button
= (Button) findViewById(R.id.defaultVibrate);
        button.setOnClickListener(
new Button.OnClickListener() {
            
public void onClick(View v) {
                setDefault(Notification.DEFAULT_VIBRATE);
            }
        });

        button
= (Button) findViewById(R.id.defaultAll);
        button.setOnClickListener(
new Button.OnClickListener() {
            
public void onClick(View v) {
                setDefault(Notification.DEFAULT_ALL);
            }
        });

        button
= (Button) findViewById(R.id.clear);
        button.setOnClickListener(
new Button.OnClickListener() {
            
public void onClick(View v) {
                mNotificationManager.cancel(NOTIFICATIONS_ID);
            }
        });

    }

    
private void setWeather(String tickerText, String title, String content,
            
int drawable) {

        Notification notification
= new Notification(drawable, tickerText,
                System.currentTimeMillis());

        PendingIntent contentIntent
= PendingIntent.getActivity(this, 0,
                
new Intent(this, ActivityMain.class), 0);

        notification.setLatestEventInfo(this, title, content, contentIntent);

        mNotificationManager.notify(NOTIFICATIONS_ID, notification);
    }

    
private void setDefault(int defaults) {

        PendingIntent contentIntent
= PendingIntent.getActivity(this, 0,
                
new Intent(this, ActivityMain.class), 0);

        
String title = "天气预报";
        
String content = "晴空万里";

        final Notification notification
= new Notification(R.drawable.sun,
                content, System.currentTimeMillis());

        notification.setLatestEventInfo(this, title, content, contentIntent);

        notification.defaults
= defaults;

        mNotificationManager.notify(NOTIFICATIONS_ID, notification);
    }
}

 

  下面开始对上述代码进行讲解

  1)因为所有的Notification都是通过NotificationManager来管理的,所以应该首先创建NotificationManager对象实例,以便管理这个Activity中信息。

  mNotificationManager=(NotificationManager)getSystemService(NOTIFICATION_SERVICE);

  2)函数setWeather是ActivityMainNotification中的重要函数之一,它实例化了一个Notification,并将这个Notification显示出来。

  3)看下面的代码。

  Notification notification = new Notification(drawable, tickerText,

  System.currentTimeMillis());

  包含了3个参数,具体说明如下。

  第一个:要显示的图片的ID。

  第二个:显示的文本文字。

  第三个:Notification显示的时间,一般是立即显示,时间就是System.currentTimeMillis()。

  4)函数setDefault也是ActivityMainNotification.java中的一个重要函数,在此函数中初始化了一个Notification,在设置Notification时使用了其默认值的形式,即:

  notification.defaults = defaults;

  另外,在上述程序中还用到了以下几种表现形式。

  Notification.DEFAULT_VIBRATE:表示当前的Notification显示出来时手机会发出震动。

  Notification.DEFAULT_SOUND:表示当前的Notification显示出来时手机会伴随音乐。

  Notification.DEFAULT_ALL:表示当前的Notification显示出来时手机即会震动,也会伴随音乐。

  这样单击第一个Button后会执行上述处理程序,来到对应的新界面,新界面的布局文件是由activity_notification.xml实现的,其主要代码如下所示。

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width
="fill_parent"
    android:layout_height
="fill_parent">
    
    
<LinearLayout
        android:orientation
="vertical"
        android:layout_width
="fill_parent"
        android:layout_height
="wrap_content">
            
        
<LinearLayout
            android:orientation
="vertical"
            android:layout_width
="fill_parent"
            android:layout_height
="wrap_content">
        
            
<Button
                android:id
="@+id/sun_1"
                android:layout_width
="wrap_content"
                android:layout_height
="wrap_content"
                android:text
="适合户外活动" />
        
            
<Button
                android:id
="@+id/cloudy_1"
                android:layout_width
="wrap_content"
                android:layout_height
="wrap_content"
                android:text
="不太适合户外活动" />
                
              
<Button
                android:id
="@+id/rain_1"
                android:layout_width
="wrap_content"
                android:layout_height
="wrap_content"
                android:text
="一点也不适合户外活动" />
                
        
</LinearLayout>
        
        
<TextView
            android:layout_width
="wrap_content"
            android:layout_height
="wrap_content"
            android:layout_marginTop
="20dip"
            android:text
="高级notification" />

        
<LinearLayout
            android:orientation
="vertical"
            android:layout_width
="fill_parent"
            android:layout_height
="wrap_content">
        
            
<Button
                android:id
="@+id/defaultSound"
                android:layout_width
="wrap_content"
                android:layout_height
="wrap_content"
                android:text
="有声音的notification" />
        
            
<Button
                android:id
="@+id/defaultVibrate"
                android:layout_width
="wrap_content"
                android:layout_height
="wrap_content"
                android:text
="振动的notification" />
                
              
<Button
                android:id
="@+id/defaultAll"
                android:layout_width
="wrap_content"
                android:layout_height
="wrap_content"
                android:text
="声音+振动的notification" />
                
        
</LinearLayout>
        
        
<Button android:id="@+id/clear"
            android:layout_width
="wrap_content"
            android:layout_height
="wrap_content"
            android:layout_marginTop
="20dip"
            android:text
="清除notification" />
            
    
</LinearLayout>

</ScrollView>

  执行后新界面的效果如图6-64所示。

对上述代码进行讲解
▲图6-64 运行效果

  当单击新图6-64中的Button后,会根据上述处理文件实现某种效果,例如,单击“有声音的Notification”按钮后,会发出声音。

  第5步:编写第二个Button的处理程序,即单击图6-63中的“介绍Toast”按钮后,执行ActivityToast.java,其主要代码如下所示。

package com.eoeandroid.toast_and_notification;

import com.eoeandroid.toast_and_notification.R;

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.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class ActivityToast extends Activity {

    OnClickListener listener1
= null;
    OnClickListener listener2
= null;
    Button button1;
    Button button2;
    
private static int NOTIFICATIONS_ID = R.layout.activity_toast;

    @Override
    
public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        listener1
= new OnClickListener() {
            
public void onClick(View v) {
                setTitle(
"短时显示Toast");
                showToast(Toast.LENGTH_SHORT);

            }
        };
        listener2
= new OnClickListener() {
            
public void onClick(View v) {
                setTitle(
"长时显示Toast");
                showToast(Toast.LENGTH_LONG);
                showNotification();
            }
        };
        setContentView(R.layout.activity_toast);
        button1
= (Button) findViewById(R.id.button1);
        button1.setOnClickListener(listener1);
        button2
= (Button) findViewById(R.id.button2);
        button2.setOnClickListener(listener2);
    }

    protected void showToast(
int type) {

        View view
= inflateView(R.layout.toast);

        TextView tv
= (TextView) view.findViewById(R.id.content);
        tv.setText(
"欢迎加入爬山摄影户外俱乐部,强身健体、增强友谊,共创和谐社会!");
        
/*实例化Toast*/
        Toast toast
= new Toast(this);
        toast.setView(view);
        toast.setDuration(type);
        toast.show();
    }

    
private View inflateView(int resource) {
        LayoutInflater vi
= (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        return vi.inflate(resource,
null);
    }

    protected void showNotification() {

        NotificationManager notificationManager
= (NotificationManager) getSystemService
(NOTIFICATION_SERVICE);

        CharSequence title
= "最专业的户外拓展俱乐部";
        CharSequence contents
= "户外合作论坛.com";

        PendingIntent contentIntent
= PendingIntent.getActivity(this, 0,
                
new Intent(this, ActivityMain.class), 0);

        Notification notification
= new Notification(R.drawable.default_icon,
                title, System.currentTimeMillis());

        notification.setLatestEventInfo(this, title, contents, contentIntent);

        
// 100ms延迟后,振动250ms,停止100ms后振动500ms
        notification.vibrate
= new long[] { 100, 250, 100, 500 };

        notificationManager.notify(NOTIFICATIONS_ID, notification);
    }
}

  上述处理程序是通过Toast实现的,它不需要用NotificationManager来管理,上述代码的处理流程如下。

  1)实例化Toast,每个Toast和一个View相关。

  2)设置Toast的长短,通过“showToast(Toast.LENGTH_SHORT);”来设置Toast短时间显示,通过“showToast(Toast.LENGTH_LONG);”来设置Toast长时间显示。

  3)通过函数showToast来显示Toast,具体说明如下。

  当单击“长时显示”按钮后,程序会长时间地显示提醒,并用Notification在状态栏中提示用户。

  当单击“短时显示”按钮后,程序会短时间的显示提醒。

  这样单击第二个Button后会执行上述处理程序,来到对应的新界面,新界面的布局文件是由activity_toast.xml实现的,其主要代码如下所示。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation
="vertical" android:layout_width="fill_parent"
    android:layout_height
="fill_parent">
    
<Button android:id="@+id/button1"
        android:layout_width
="wrap_content"
        android:layout_height
="wrap_content" android:text="短时显示Toast" />
    
<Button android:id="@+id/button2"
        android:layout_width
="wrap_content"
        android:layout_height
="wrap_content" android:text="长时显示Toast" />
</LinearLayout>

  执行后新界面的效果如图6-65所示。

对上述代码进行讲解
▲图6-65 运行效果

对上述代码进行讲解
▲图6-66 运行效果

  当单击新图6-65中的Button后,会根据上述处理文件而实现某种效果,例如,单击“短时显示Toast”按钮后,会短时间显示一个提醒,当单击“长时显示Toast”按钮后,会长时间显示一个提醒,两种方式的提醒界面都是相同的,具体效果如图6-66所示。

  至此,整个实例介绍完毕,读者可以阅读随书光盘中的源代码,来了解更加具体的信息。

0
相关文章