天天看点

第八章 丰富你的程序-运用手机多媒体

8.1 将程序运行到手机上

8.2 使用通知(Notification)

    第一步,获取通知管理器

    NotificationManager manger = (NotificationManager)

        getSystemService(Context.NOTIFICATION_SERVICE);

    Notification notification = new NotificationCompat.Builer(context).build();

    如果是安卓8.0以上的系统,则要添加以下代码

    String channelId = "chat";

    String channelName = "聊天消息";

    int importance = NotificationManager.IMPORTANCE_HIGH;

    NotificationChannel channel = null;

            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {//

                channel = new NotificationChannel(channelId,channelName,importance);//第二步

                manager.createNotificationChannel(channel);//第三步

            } else {

                Log.d("MainActivity", "error ");

            }

    同时修改    Notification notification = new NotificationCompat.Builer(context, channelId)

    第二步,创建一个Notification对象

    Notification notification = new NotificationCompat.Builer(context)

        .setContentTitle("This is content title")

        .setContentText("This si content test)

        .setWhen(System.currentTimeMillis())

        .setSmallIcon(R.drawable.small_icon)

        .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.large_icon))

        .build();

    第三步,调用NotificationManager的notify()方法

    manager.notify(1, notification);        第一个参数表示第个通知的ID号,第二个参数表示Notification对象

    第四步,产生点击进入活动效果

        先新建一个NotificationActivity活动,

        然后再, 

            Intent intent = new Intent(this, NotificationActivity.class);

            PendingIntent pi = PendingIntent.getActivity(this, 0, intent, 0);

            第一个参数,表示上下文,第三个参数表示一个Intent对象,第二,四个一般传0,0;

            在原来的基础上添加, setContentIntent(pi)

            再点击会启动intent;

    第五步,点击,取消通知效果

        方案一, 在基础上添加,setAutoCanel(true)

        方案二,    intent活动中,onCreate添加如下代码:

                NotificationManager  manaer= (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

                manager.canel(1);    参数为通知的ID号

    8.2.2 通知的进阶技巧

        .setSound(uri.fromFile(new File("/system/media/audio/ringtones/Luna.ogg")));

        设置通知的声音

        setVibrate(new long[] {0,300,500,700});

        振动:延迟0ms,然后振动300ms,在延迟500ms, 接着再振动700ms

        还要添加权限

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

        setLights(color.GREEN, 5000, 1000)

        设置颜色,第二,三参数表示,明,暗的时长,

        如果不想设置,可以使用默认设置,如

        setDefaults(NoticicationCompat.DEFAULT_ALL)

    8.2.3 通知的高级功能 

        .setStyle("可以放很长的文本")

        在通知时是可以显示的

        .setStyle(new NotificationCompat.BigPictureStyle().bigPicture(

            BitmapFactory.decodeResource(getResource(), R.drawable.big_image)))

        在通知栏上显示图片

        .setPriority(NotificationCompat.PRIORITY_MAX)

        将通知的重要程度设置到最高,手机会在任何时候显示通知

    8.3 调用摄像头和相册

    8.4 播放多媒体文件

继续阅读