android基础学习之通知

来源:互联网 发布:java 301跳转 编辑:程序博客网 时间:2024/05/20 13:36

一般来说android的通知有3中方式,第一种是通过toast直接打印在屏幕上,第二种是对话框的形式,第三种是以通知的形式,在通知的形式中以下提供的方法仅仅适用于api16或者更高的版本,代码中有详细注解

package com.example.notificationdemo;import android.os.Bundle;import android.app.Activity;import android.app.AlertDialog;import android.app.Notification;import android.app.NotificationManager;import android.app.PendingIntent;import android.content.Context;import android.content.DialogInterface;import android.content.DialogInterface.OnClickListener;import android.content.Intent;import android.view.Menu;import android.view.View;import android.widget.Toast;public class MainActivity extends Activity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);}public void onMyClick(View v) {int id = v.getId();switch (id) {case R.id.btn_toast:Toast.makeText(this, "我是toast", Toast.LENGTH_SHORT).show();break;case R.id.btn_dialog://创建builder对象AlertDialog.Builder builder = new AlertDialog.Builder(this);   builder.setTitle("标题").setMessage("我是Alertdialog").setPositiveButton("我知道", new OnClickListener() {@Overridepublic void onClick(DialogInterface arg0, int arg1) {// 设置确定按钮的相应的点击事件}});//通过builder对象创建dialogAlertDialog dialog=builder.create();//显示dialogdialog.show();break;case R.id.btn_notification://创建builder对象Notification.Builder notibuilder = new Notification.Builder(this);notibuilder.setTicker("Tiker").setContentTitle("你傻吗").setContentText("你才傻");//创建intent对象Intent intent = new Intent(this, MainActivity.class);//通过intent对象创建PendingIntent对象PendingIntent pintent = PendingIntent.getActivity(this, 0,intent, PendingIntent.FLAG_UPDATE_CURRENT);//将PendingIntent对象给buildernotibuilder.setContentIntent(pintent);//创建notification对象Notification notification=notibuilder.build();//获取系统的状态栏通知服务NotificationManager nm=(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);//显示我们的notificationnm.notify(1000,notification);break;  }}}


0 0