您的位置:首页 > 移动开发 > Android开发

Android笔记(二十八)通知的使用

2015-09-10 11:41 441 查看

一、通知的用法

当某个应用程序希望向用户发出一些提示信息,而该应用程序又不在前台运行时,就可以借助通知来实现。相比于广播***和服务,在活动里创建通知的场景还是比较少的,因为一般只有当程序进入到后台的时候我们才需要使用通知。

获得NotificationManager 的实例

创建一个 Notification 对象

设定通知的布局

调用 NotificationManager 的 notify()方法

二、具体实例——通过点击按钮来发出一条通知

建立布局

<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

public class MainActivity extends ActionBarActivity {

    private Button button;
    private NotificationManager manager;
    private Notification.Builder builder;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button = (Button) findViewById(R.id.send_notice);
        button.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
                builder = new Notification.Builder(MainActivity.this);
                Intent intent = new Intent(MainActivity.this,
                        MainActivity.class);
                PendingIntent contentIntent = PendingIntent.getActivity(
                        MainActivity.this, 0, intent, 0);
                builder.setContentIntent(contentIntent);
                builder.setTicker("这是一个通知");
                builder.setContentTitle("通知");
                builder.setContentText("hello");
                builder.setDefaults(Notification.DEFAULT_ALL);
                builder.setSmallIcon(R.drawable.ic_launcher);
                Notification notification = builder.build();
                manager.notify(1, notification);
            }
        });
    }
    }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: