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

来源:互联网 发布:阿里妈妈和淘宝联盟 编辑:程序博客网 时间:2024/04/29 22:10

8.1使用通知

当应用程序不在前台是,通过通知向用户发送提示消息.发送后,最上方的状态栏会显示通知的图标.,下拉后可以看到详细内容.

8.1.1通知的基本用法

通知可以由活动/服务/广播接收器创建.
- 调用Context的getSystemService()获得NotificationManager用于管理通知.

NotificationManager manager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
  • 创建Notification对象用于储存通知所需要的信息.三个参数分别是通知的图标,通知的ticker内容,通知被创建的时间,单位是毫秒.
Notification notification = new Notification(R.drawable.icon, "This is ticker text",System.currentTimeMillis());
  • 设定通知布局.第二个参数用于指定通知的标题内容,第三个参数用于指定通知的正文内容.
notification.setLatestEventInfo(context, "This is content title", "This is content text", null);
  • 调用NotificationManager的notify()显示通知.第一个参数是id,保证每个通知指定的id是不同的,第二个参数时Notification对象.
manager.notify(1,Notification);

示例(别信书上的…书上太老了):

public void onClick(View v){    switch (v.getId()){        case R.id.send_notice:            NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);            Notification notification = new Notification.Builder(this)                    .setAutoCancel(true)                    .setContentTitle("title")                    .setContentText("describe")                                       .setSmallIcon(R.mipmap.ic_launcher)                    .setWhen(System.currentTimeMillis())                    .build();            manager.notify(1,notification);            break;        default:            break;    }}
  • 通过PendingIntent实现通知的点击效果.pendingIntent可以用于启动活动,服务或发送广播.通过getActivity()/getBroadcast()/getService().这几个方法所接收的参数都是相同的,第一个参数依旧是 Context,不用多做解释。第二个参数一般用不到,通常都是传入 0 即可。第三个参数是一个 Intent 对象,我们可以通过这个对象构建出 PendingIntent 的“意图”。第四个参数用于确定 PendingIntent 的行为,有FLAG_ONE_SHOT、 FLAG_NO_CREATE、 FLAG_CANCEL_CURRENT 和 FLAG_UPDATE_CURRENT 这四种值可选.
    • FLAG_CANCEL_CURRENT:如果当前系统中已经存在一个相同的PendingIntent对象,那么就将先将已有的PendingIntent取消,然后重新生成一个PendingIntent对象。
    • FLAG_NO_CREATE:如果当前系统中不存在相同的PendingIntent对象,系统将不会创建该PendingIntent对象而是直接返回null。
    • FLAG_ONE_SHOT:该PendingIntent只作用一次,如果该PendingIntent对象已经触发过一次,那么下次再获取该PendingIntent并且再触发时,系统将会返回一个SendIntentException,在使用这个标志的时候一定要注意哦。
    • FLAG_UPDATE_CURRENT:如果系统中已存在该PendingIntent对象,那么系统将保留该PendingIntent对象,但是会使用新的Intent来更新之前PendingIntent中的Intent对象数据,例如更新Intent中的Extras。这个非常有用,例如之前提到的,我们需要在每次更新之后更新Intent中的Extras数据,达到在不同时机传递给MainActivity不同的参数,实现不同的效果。
      示例:
Intent intent = new Intent(this,NotificationActifity.class);PendingIntent pi = PendingIntent.getActivity(this,0,intent,PendingIntent.FLAG_CANCEL_CURRENT);NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);Notification notification = new Notification.Builder(this)        .setAutoCancel(true)        .setContentTitle("title")        .setContentText("describe")        .setContentIntent(pi)        .setSmallIcon(R.mipmap.ic_launcher)        .setWhen(System.currentTimeMillis())        .build();manager.notify(1,notification);

8.1.2通知的高级技巧

  • Notification的sound属性,用于通知发出是播放音频,该属性是一个URI对象.
Uri soundUri = Uri.fromFile(new File("/system/media/audio/ringtones/Basic_tone.ogg"));notification.sound = soundUri;
  • Notification的vibrate属性,用于控制手机的震动.是一个长整形数组.毫秒为单位,数组下标为单数,静止时长;下标为双数,震动时长.
long[] vibrates = {0, 1000, 1000, 1000};notification.vibrate = vibrates;
  • Notification的ledARGB,ledOnMS,ledOffMS,flags.flags用于指定通知的一些行为,包括显示LED.
    示例(绿灯,亮一秒熄一秒):
notification.ledARGB = Color.GREEN;notification.ledOnMS = 1000;notification.ledOffMS = 1000;notification.flags = Notification.FLAG_SHOW_LIGHTS;
  • 使用默认设置:
notification.defaults = Notification.DEFAULT_ALL;

8.2接受和发送短信

8.2.1接收短信

class MessageReceive extends BroadcastReceiver{    @Override    public void onReceive(Context context,Intent intent){        Bundle bundle = intent.getExtras();        Object[] pdus = (Object[]) bundle.get("pdus");        SmsMessage[] messages = new SmsMessage[pdus.length];        for(int i=0;i<messages.length;i++){            messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);        }        String address = messages[0].getOriginatingAddress();        String fullMessage = "";        for(SmsMessage message : messages){            fullMessage += message.getMessageBody();        }        sender.setText(address);        content.setText(fullMessage);    }}

注意:

Android设备接收到的SMS是以pdu形式的(protocol description unit)。所以从intent提取数据时就会遇到pdus。

8.2.2发送短信

有序广播是可以被截断的,而系统发出的短信广播是一条有序广播.先提高MessageReceive的优先级,再在onReceive()中调用abortBroadcast()中止即可.

示例:

sendFilter = new IntentFilter();sendFilter.addAction("SENT_SMS_ACTION");sendStatusReceiver = new SendStatusReceiver();registerReceiver(sendStatusReceiver, sendFilter);msgInput = (EditText) findViewById(R.id.msg_input);send = (Button) findViewById(R.id.send);send.setOnClickListener(new View.OnClickListener() {    @Override    public void onClick(View v) {        SmsManager smsManager = SmsManager.getDefault();        Intent sentIntent = new Intent("SENT_SMS_ACTION");        PendingIntent pi = PendingIntent.getBroadcast(MainActivity.this, 0, sentIntent, 0);        smsManager.sendTextMessage(to.getText().toString(), null, msgInput.getText().toString(), pi, null);    }});

8.3调用摄像头和相册

8.3.1将程序运行到手机上

略…

8.3.1从相册中选择照片

略…
相信我,如果你习惯筛选自己的名字来输出日志,千万千万记得把异常也用一样的方式输出 :)

8.4播放多媒体文件

8.4.1播放音频

Android中播放音频一般使用MediaPlayer实现.
常用方法:
- setDataSource():设置要播放的音频文件的位置
- prepare():在开始播放之前调用这个方法完成准备工作
- start():开始或继续播放音频。
- pause(): 暂停播放音频。
- reset(): 将 MediaPlayer 对象重置到刚刚创建的状态。
- seekTo(): 从指定的位置开始播放音频。
- stop(): 停止播放音频。调用这个方法后的 MediaPlayer 对象无法再播放音频。
- release(): 释放掉与 MediaPlayer 对象相关的资源。
- isPlaying(): 判断当前 MediaPlayer 是否正在播放音频。
- getDuration(): 获取载入的音频文件的时长。

注意:

读取SD卡文件需要获取权限.

8.4.2播放视频

Android中播放视频一般使用VideoView实现.
- setVideoPath(): 设置要播放的视频文件的位置。
- start(): 开始或继续播放视频。
- pause(): 暂停播放视频。
- resume(): 将视频重头开始播放。
- seekTo(): 从指定的位置开始播放视频。
- isPlaying(): 判断当前是否正在播放视频。
- getDuration(): 获取载入的视频文件的时长。

0 0