android之Notification实现

在我们的相应程序运行的时候为了不打断当前程序的运行,我们经常会使用Notification来告知用户有新来电或新的短信。

下面先介绍一下toast的简单提醒:

private void baseToast(){ Toast.makeText(getApplicationContext(), "Hello toast!", Toast.LENGTH_SHORT).show(); } 第一个参数是得到上下文,第二个是提醒的具体内容,第三个是提醒的时间。


接下来看一下如何自定义一个Toast提醒:


//自定义toast private void customToast(){ //得到inflater对象和view LayoutInflater inflater=getLayoutInflater(); View layout=inflater.inflate(R.layout.toast_layout, (ViewGroup) findViewById(R.id.toast_layout_root)); //得到view下的相应的控件 ImageView image = (ImageView) layout.findViewById(R.id.image); image.setImageResource(R.drawable.ic_launcher); TextView text = (TextView) layout.findViewById(R.id.text); text.setText("Hello! This is a custom toast!"); //设置toast Toast toast=new Toast(getApplicationContext()); toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0); toast.setDuration(Toast.LENGTH_SHORT); toast.setView(layout); toast.show(); } 在layout 下定义了toast_layout.xml布局文件:

<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/toast_layout_root" android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="fill_parent" android:padding="10dp" android:background="#DAAA" > <ImageView android:id="@+id/image" android:layout_width="wrap_content" android:layout_height="fill_parent" android:layout_marginRight="10dp" /> <TextView android:id="@+id/text" android:layout_width="wrap_content" android:layout_height="fill_parent" android:textColor="#FFF" /> </LinearLayout>
运行后效果:

我们自定义的toast要比系统默认的好多了,当然如果愿意还可以自定义更复杂好看的Toast。

下面看一下Notification通知的一个例子:

private void showNotification(){ //得到一个NotificationManager对象 NotificationManager manager=(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); //实例化一个Notification int icon=R.drawable.ic_launcher; CharSequence text = "未接电话通知"; long when=System.currentTimeMillis(); Notification notification=new Notification(icon, text, when); //设置最新事件消息和PendingIntent Context context = getApplicationContext(); CharSequence contentTitle = "你好"; CharSequence contentText = "你的未接电话!"; Intent intent=new Intent(Intent.ACTION_CALL,Uri.parse("tel:5554")); PendingIntent pendingIntent=PendingIntent.getActivity(this, 0, intent, 0); notification.setLatestEventInfo(context, contentTitle, contentText, pendingIntent); //启动提醒 manager.notify(1, notification); } 该例子中用到了拨打电话所以不要忘了添加权限:

<uses-permission android:name="android.permission.CALL_PHONE"/>
运行后效果:


把上面提示栏拉下来后:


点击相应的内容就会拨打电话了:



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值