【总结】Android攻城狮之Notification

本文介绍了Android系统的Notification功能,包括如何创建、发送及取消通知栏消息,并通过实例展示了Notification的使用方法,如设置提示音、指示灯及震动效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Android攻城狮之Notification

目录

Notification简介

  Notification是显示在手机状态栏的消息(手机状态栏位于手机最顶端),代表一种全局效果的通知。

获取NotificationMananger

  显示通知栏: notify(id,notification);
  取消通知栏: cancle(id);
  构造Notification并设置显示内容
  通知栏通知可以设置声音提示,指示灯,以及震动效果。

AlertDialog实例

public class MainActivity extends Activity implements DialogInterface.OnClickListener{
    NotificationManager manager;
    int notification_ID;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        manager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
        findViewById(R.id.btn_send).setOnClickListener(this);
        findViewById(R.id.btn_cancle).setOnClickListener(this);

    }
    @Override
    private void OnClick(View view){
        switch (view.getId()){
            case R.id.btn_send:
                sendNotification();
                break;
            case R.id.btn_cancle:
                manager.cancel(notification_ID);
                break;
        }
    /**
     * 构造notification并发送到通知栏
     */
    private void sendNotification(){
        Intent intent = new Intent(this, MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,0);
        Notification.Builder builder = new Notification.Builder(this);
        builder.setSmallIcon(R.drawable.ic_launcher);//设置图标
        builder.setTicker("Hello");//手机状态栏的提示
        builder.setWhen(System.currentTimeMillis());//设置时间
        builder.setContentTitle("通知栏通知");//设置标题
        builder.setContentText("我来自NotificationDemo");//设置内容
        builder.setContentIntent(pendingIntent);//点击后的意图
        builder.setDefaults(Notification.DEFAULT_SOUND);//设置提示音
        builder.setDefaults(Notification.DEFAULT_LIGHTS);//设置提示灯
        builder.setDefaults(Notification.DEFAULT_VIBRATE);//设置震动
//      builder.setDefaults(Notification.DEFAULT_ALL);//等同于上面三行代码
        Notification notification = builder.build();//需要API level 16
//      builder.getNotification();//API level低于16时使用
        manager.notify(notification_ID, notification);
    }

  同时要进行权限的设置,在AndroidManifest.xml文件中添加以下权限

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

  最后效果如下:

  

通知栏消息提示        通知栏消息显示

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值