• Android里的多媒体


    一、通知:即显示在手机下滑框的消息。

           NotificationManager:通知管理器, 用来发送通知

                     有以下方法:

         (NotificationManager)getSystemService(NOTIFICATION_SERVICE):获得NotificationManager
         notify(int,Notification):发送通知,传入通知的id(每个通知都不能相同)和要发送的通知

           Notification.Builder:通知构建器,用来构建通知和设置通知各种参数

                     有以下方法:

    		new Notification.Builder(Context):构建一个Notification.Builder
    		builder.setSmallIcon(R.drawable.ic_launcher); //设置图标
    		builder.setTicker("小红给你发来了一条信息");	  //显示最先在顶部收到的通知 
    		builder.setContentTitle("通知"); 	//设置标题
    		builder.setContentText("点击查看详细内容"); //消息内容
    		builder.setWhen(System.currentTimeMillis()); //发送时间
    		builder.setDefaults(Notification.DEFAULT_ALL); //设置默认的提示音,振动方式,光
    		builder.setAutoCancel(true);//打开程序后图标消失
                    builder.setSmallIcon(R.mipmap.ic_launcher)//设置小图标
                    builder.setWhen(System.currentTimeMillis())//设置通知的时间
    
    		//设置通知播放音频,指定路径下的音频
    		builder.setSound(Uri.fromFile(new File("音频路径")));
    		//设置通知振动:下标为偶数表示静止时长,奇数为振动时长,单位为毫秒
    		//需在注册地方声明权限:
                    //<uses-permission android:name="android.permission.VIBRATE" />
    		long[] vibrates= {0,1000,1000,1000};//此时立即振动,然后静止一秒,再振动一次
    		builder.setVibrate(vibrates);
    		
    		//设置通知响应的事件Activity,PendingIntent可以理解为延迟的Intent
    		Intent intent =new Intent (this,NotificationLayout.class);
    		PendingIntent pendingIntent =PendingIntent.getActivity(this, 0, intent,0);
    		builder.setContentIntent(pendingIntent);
    		
    		//构建一条通知Notification
    		Notification notification=builder.build();

            Notification:通知类,通过Notification.Builder的build()方法获得

               builder.build():构建一个Notification

    完整例子:

    public void onClick(View v) {
    		switch(v.getId()) {
    		case R.id.sendNotice:
    			NotificationManager manager=            
                      (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
    			Notification.Builder builder=new Notification.Builder(this);
    			builder.setSmallIcon(R.drawable.ic_launcher); //设置图标
    			builder.setTicker("小红给你发来了一条信息");	  //显示最先在顶部收到的通知 
    			builder.setContentTitle("通知"); 	//设置标题
    			builder.setContentText("点击查看详细内容"); //消息内容
    			builder.setWhen(System.currentTimeMillis()); //发送时间
    			builder.setDefaults(Notification.DEFAULT_ALL); //设置默认的提示音振动方式灯光
    			builder.setAutoCancel(true);//打开程序后图标消失
    			//设置通知播放音频,指定路径下的音频
    			builder.setSound(Uri.fromFile(new 
                                  File("/system/media/audio/ringtones/Basic_tone.ogg")));
    			//设置通知振动:下标为偶数表示静止时长,奇数为振动时长,单位为毫秒
    			//(需在注册地方声明权限:
                            //<uses-permission android:name="android.permission.VIBRATE" />)
    			long[] vibrates= {0,1000,1000,1000};//此时立即振动,然后静止一秒,再振动一次
    			builder.setVibrate(vibrates);
    			
    			//设置通知响应的事件Activity,PendingIntent可以理解为延迟的Intent
    			Intent intent =new Intent (this,NotificationLayout.class);
    			PendingIntent pendingIntent =PendingIntent.getActivity(this, 0, intent,0);
    			builder.setContentIntent(pendingIntent);
    			
    			Notification notification=builder.build();
    			manager.notify(1,notification);
    			
    		}
    	}

    二、短信

    发送短信和接收短信涉及权限:

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

           接收短信:当系统收到短信时会自动发送广播"android.provider.Telephony.SMS_RECEIVED"

           1、自定义广播接收器类

    
    	class MessageReceiver extends BroadcastReceiver{
    		//接收到系统短信广播进行的操作
    		@Override
    		public void onReceive(Context context, Intent intent) {
    			Bundle bundle=intent.getExtras();
    			Object[] pdus=(Object[])bundle.get("pdus");	//提取短信消息
    			SmsMessage[] message=new SmsMessage[pdus.length];
    	                String format = intent.getStringExtra("format");
    			for(int i=0;i<message.length;i++) {
    				message[i]=SmsMessage.createFromPdu((byte[])pdus[i],format);
    			}
    			String address=message[0].getOriginatingAddress();//获取发送方号码
    			String fullMessage="";
    			for(SmsMessage body:message) {
    				fullMessage+=body.getMessageBody();//获取短信内容
    			}
    			sender.setText(address);
    			content.setText(fullMessage);
    		}
    	}

          2、主活动onCreate()里注册广播接收器和onDestroy()取消注册广播接收器

    protected void onCreate(Bundle savedInstanceState) {
    		super.onCreate(savedInstanceState);
    		setContentView(R.layout.activity_main);
    		//接收短信部分
    		sender=(TextView)findViewById(R.id.sender);
    		content=(TextView)findViewById(R.id.content);
    		messageReceiver=new MessageReceiver();
    		intentfilter=new IntentFilter();
    		intentfilter.addAction("android.provider.Telephony.SMS_RECEIVED");
    		registerReceiver(messageReceiver, intentfilter);
        }
    public void onDestroy() {
    		super.onDestroy();
    		//取消注册接收信息的广播接收器
    		unregisterReceiver(messageReceiver);
        }

           发送短信:在onCreate()里利用SmsManager发送短信,增加了一个广播接收器判断短信是否发出
     

    class sendStatusReceiver extends BroadcastReceiver{
    		//接收发送广播状态的广播,进行判断
    		@Override
    		public void onReceive(Context context, Intent intent) {
    			if(this.getResultCode()==RESULT_OK) {
    				Toast.makeText(context, "Send succeed", Toast.LENGTH_SHORT).show();
    			}else {
    				Toast.makeText(context, "Send failed", Toast.LENGTH_SHORT).show();
    			}
    		}
    }
    protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            //发送短信部分
            to=(EditText)findViewById(R.id.to);
            msgInput=(EditText)findViewById(R.id.input);
            send=(Button)findViewById(R.id.send);
            intentfilter=new IntentFilter();
            intentfilter.addAction("SENT_SMS_ACTION");
            sendStatusReceiver=new sendStatusReceiver();
            registerReceiver(sendStatusReceiver,intentfilter);
            send.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    SmsManager smsManager=SmsManager.getDefault();
                    Intent sendIntent=new Intent("SENT_SMS_ACTION");
                    PendingIntent pi=PendingIntent.getBroadcast(MainActivity.this, 0,     
                     sendIntent, 0);
                    smsManager.sendTextMessage(to.getText().toString(), null, 
                       msgInput.getText().toString(),pi, null);
                }
                
            });
    }
    public void onDestroy() {
    	super.onDestroy();
    	//取消注册接收发送信息状态变化的广播
    	unregisterReceiver(sendStatusReceiver);
    }

    三、打开相机和打开相册:代码都有注释直接看代码

    需要读权限
       

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

    不需要写权限

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

    布局文件:

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/LinearLayout1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:paddingBottom="@dimen/activity_vertical_margin"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
        tools:context="com.example.mediatest.MainActivity" >
    
        <Button
            android:id="@+id/choose_photo"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Choose photo" />
    
        <Button
            android:id="@+id/take_photo"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Take photo" />
    
        <ImageView
            android:id="@+id/picture"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal" />
    
    </LinearLayout>
    

    对应活动代码:

    public class MainActivity extends Activity {
    	private Button takePhoto;
    	private Button choosePhoto;
    	private ImageView picture;
    	private Uri imageUri;
    	@Override
    	protected void onCreate(Bundle savedInstanceState) {
    		super.onCreate(savedInstanceState);
    		setContentView(R.layout.activity_main);
    		takePhoto=(Button) findViewById(R.id.take_photo);
    		picture = (ImageView) findViewById(R.id.picture);
    		takePhoto.setOnClickListener(new OnClickListener() {
    			@Override
    			public void onClick(View v) {
    				// TODO Auto-generated method stub
    				File outputPicture = new File(getExternalCacheDir(), "why.jpg");
    		        if (outputPicture.exists()) {//如果照片文件存在则删除
    		            outputPicture.delete();
    		        }
    		        try {
    		            outputPicture.createNewFile();//创建一个新照片文件
    		        } catch (IOException e) {
    		            e.printStackTrace();
    		        }
    		        //"android.media.action.IMAGE_CAPTURE"用来隐式启动活动来启动相机
    		        imageUri = Uri.fromFile(outputPicture);//将文件解析成Uri
    		        Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
    		        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
    		        startActivityForResult(intent, 1);//启动相机程序,并返回onActivityResult()方法
    			}
    		});
    		choosePhoto=(Button)findViewById(R.id.choose_photo);
    		choosePhoto.setOnClickListener(new OnClickListener() {
    			@Override
    			public void onClick(View v) {
    				//将活
    				Intent intent=new Intent("android.intent.action.GET_CONTENT");
    				intent.setType("image/*");	//设置启动类型为照片,此时结果为3对应活动打开相册
    				startActivityForResult(intent,3);
    			}
    			
    		});
    	}
    	@Override
        protected void onActivityResult(int requestCode, int result, Intent data) {
            switch (requestCode) {
        		//裁剪照片
                case 1:
                    if(result==RESULT_OK) {
                    	Intent intent=new Intent("com.android.camera.action.CROP");
                    	//Data是指储存的数据(即当前照片的Uri)
                    	//Type是启动的类型:目前为照片(一般在需要裁剪照片和启动相机时使用)
                    	intent.setDataAndType(imageUri, "image/*");
                    	intent.putExtra("scale", true);
                    	intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
                    	startActivityForResult(intent,2);
                    }
                //压缩照片并显示
                case 2:
                	if (result == RESULT_OK) {
                        try {
                        	//获取图片
                            Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri));
                            //压缩图片在手机存储空间的内存  
                            ByteArrayOutputStream out = new ByteArrayOutputStream();
                            bitmap.compress(Bitmap.CompressFormat.JPEG, 80, out);//80指保留80品质,压缩20品质
                            
                            //显示照片
                            picture.setImageBitmap(bitmap);
    
                        } catch (FileNotFoundException e) {
                            e.printStackTrace();
                        }
                    }
                    break;
                //打开相册
                case 3:
                	if (result == RESULT_OK) {
                		//必须重写handleImageOnKitKat(Intent)和handleImageBeforeKitKat(Intent)方法
    	            	if(Build.VERSION.SDK_INT>=19) {
    	                    //4.4(API 19)以上版本实现打开相册
    	                    handleImageOnKitKat(data);
    	            	}
    	            	else {
    	            		//4.4以下版本实现打开相册
    	            		handleImageBeforeKitKat(data);
    	            	}
                	}
                    break;
            }
        }
    
        private void handleImageBeforeKitKat(Intent data) {
    		Uri uri=data.getData();
    		String imagePath=getImagePath(uri,null);
    		showImage(imagePath);
    	}
    	@TargetApi(Build.VERSION_CODES.KITKAT)
    	@SuppressLint("NewApi")
    	private void handleImageOnKitKat(Intent data) {
            //获取资源定位符
            Uri uri = data.getData();
            String imagePath=getImagePath(uri);
            showImage(imagePath);
        }
    	//解析Uri返回图片路径
        @SuppressLint("NewApi")
    	private String getImagePath(Uri uri) {
        	//选择图片路径
            String imagePath = null;
            if (DocumentsContract.isDocumentUri(this, uri)) {
                String docId = DocumentsContract.getDocumentId(uri);
                if ("com.android.providers.media.documents".equals(uri.getAuthority())) {
                    String id = docId.split(":")[1];
                    String selection = MediaStore.Images.Media._ID + "=" + id;
                    imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);
                } else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())) {
                    Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(docId));
                    imagePath = getImagePath(contentUri, null);
                }
    
            } else if ("content".equalsIgnoreCase(uri.getScheme())) {
                imagePath = getImagePath(uri, null);
            } else if ("file".equalsIgnoreCase(uri.getScheme())) {
                imagePath = uri.getPath();
            }
    		return imagePath;
        }
        //子方法:根据Uri和selection返回图片路径
        private String getImagePath(Uri externalContentUri, String selection) {
            String path = null;
            Cursor cursor = getContentResolver().query(externalContentUri, null, selection, null, null);
            if (cursor != null) {
                if (cursor.moveToFirst()) {
                    path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
                }
                cursor.close();
            }
            return path;
        }
        //根据图片路径显示图片
        private void showImage(String imagePath) {
            if (imagePath != null) {
                Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
                /*
                   setlmageBitmap(Bitmap bm):使用 Bitmap 位图设置该 ImageView 显示的图片。
    
    			   setlmageDrawable(Drawable drawable):使用 Drawable 对象设置该 ImageView 显示的图片。
    
    			   setlmageResource(int resld):使用图片资源ID设置该ImageView显示的图片。
    
    			   setlmageURI(Uri uri):使用图片的URI设置该ImageView显示的图片。
                 */
                picture.setImageBitmap(bitmap);
            } else {
                Toast.makeText(this, "没有找到对应图片", Toast.LENGTH_SHORT).show();
            }
        }
    }
    

    四、播放音频和视频

    补充知识:

    1、需要读取权限

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

    2、获取系统内存根目录位置方法和SD卡根目录位置方法

    //内存根目录获取方法:Environment.getExternalStorageDirectory()
    
    //获取SD卡根路径方法:
    public static String getSDPath(Context context) {  
    
          StorageManager mStorageManager = (StorageManager)
                    context.getSystemService(Context.STORAGE_SERVICE);
            Class<?> storageVolumeClazz = null;
            try {
                storageVolumeClazz = Class.forName("android.os.storage.StorageVolume");
                Method getVolumeList = mStorageManager.getClass().getMethod("getVolumeList");
                Method getPath = storageVolumeClazz.getMethod("getPath");
                Method isRemovable = storageVolumeClazz.getMethod("isRemovable");
                Object result = getVolumeList.invoke(mStorageManager);
                final int length = Array.getLength(result);
                for (int i = 0; i < length; i++) {
                    Object storageVolumeElement = Array.get(result, i);
                    String path = (String) getPath.invoke(storageVolumeElement);
                    boolean removable = (Boolean) isRemovable.invoke(storageVolumeElement);
                    if (removable) {
                        return path;
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
    }

    1、播放音频:使用MediaPlayer类

               MediaPlayer类有以下方法:

               setDataSource():设置播放音频文件位置

               prepare():在开始播放前调用此方法完成准备工作

               start():开始或继续播放音频

               pause():暂停播放音频

               reset():将MediaPlayer对象重置到刚刚创建状态

               seekTo():从指定位置开始播放音频

               stop():停止播放音频

               release():释放掉与MediaPlayer对象相关资源

               isPlaying():判断是否正在播放音频

               getDuration():获取载入的音频文件时长

    2、播放视频:使用VideoView类

               VideoView类有以下方法:

               setVideoPath():设置视频文件位置

               start():开始或继续播放视频

               pause():暂停播放视频

               resume():将视频从头开始播放

               seekTo():从指定位置开始播放视频

               isPlaying():判断是否正在播放视频

               getDuration():获取载入的视频文件时长

    播放音频完整代码演示

    public class MusicActivity extends Activity implements OnClickListener{
    	private Button play;
    	private Button pause;
    	private Button stop;
    	private MediaPlayer mediaPlayer=new MediaPlayer();
    	protected void onCreate(Bundle savedInstanceState) {
    		super.onCreate(savedInstanceState);
    		setContentView(R.layout.music);
    		play=(Button)findViewById(R.id.play);
    		pause=(Button)findViewById(R.id.pause);
    		stop=(Button)findViewById(R.id.stop);
    		play.setOnClickListener(this);
    		pause.setOnClickListener(this);
    		stop.setOnClickListener(this);
    		initMediaPlayer();
    	}
    
    
    
    
    //获取SD卡根路径方法:
    public static String getSDPath(Context context) {  
    
          StorageManager mStorageManager = (StorageManager) context.getSystemService(Context.STORAGE_SERVICE);
            Class<?> storageVolumeClazz = null;
            try {
                storageVolumeClazz = Class.forName("android.os.storage.StorageVolume");
                Method getVolumeList = mStorageManager.getClass().getMethod("getVolumeList");
                Method getPath = storageVolumeClazz.getMethod("getPath");
                Method isRemovable = storageVolumeClazz.getMethod("isRemovable");
                Object result = getVolumeList.invoke(mStorageManager);
                final int length = Array.getLength(result);
                for (int i = 0; i < length; i++) {
                    Object storageVolumeElement = Array.get(result, i);
                    String path = (String) getPath.invoke(storageVolumeElement);
                    boolean removable = (Boolean) isRemovable.invoke(storageVolumeElement);
                    if (removable) {
                        return path;
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
    }
    	@Override
    	public void onClick(View v) {
    		switch(v.getId()) {
    		case R.id.play:
    			if(!mediaPlayer.isPlaying()) {
    				mediaPlayer.start();
    			}break;
    		case R.id.pause:
    			if(mediaPlayer.isPlaying()) {
    				mediaPlayer.pause();
    			}break;
    		case R.id.stop:
    			if(mediaPlayer.isPlaying()) {
    				mediaPlayer.reset();
    				initMediaPlayer();
    			}break;
    		default:break;
    		}
    	}
    	public void onDestroy() {
    		super.onDestroy();
    		if(mediaPlayer!=null) {
    			mediaPlayer.stop();
    			mediaPlayer.release();
    		}
    	}
    	//初始化音频文件方法:设置音频位置,完成准备工作
    	private void initMediaPlayer() {
    		try {
    			File file=new File(getSDPath(this),"aiying.mp3");
    			mediaPlayer.setDataSource(file.getPath());
    			mediaPlayer.prepare();
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
    	}
    }
    

    播放视频完整代码演示

    public class VedioActivity extends Activity implements OnClickListener{
    	private VideoView videoView;
    	private Button play;
    	private Button pause;
    	private Button replay;
    	
    	protected void onCreate(Bundle savedInstanceState) {
    		super.onCreate(savedInstanceState);
    		setContentView(R.layout.vedio);
    		videoView=(VideoView)findViewById(R.id.videoView1);
    		play=(Button)findViewById(R.id.play_vieo);
    		pause=(Button)findViewById(R.id.pause_vieo);
    		replay=(Button)findViewById(R.id.replay);
    		play.setOnClickListener(this);
    		pause.setOnClickListener(this);
    		replay.setOnClickListener(this);
    		initVideoPath();
    	}
    	private void initVideoPath() {
    		File file=new File(Environment.getExternalStorageDirectory(),"tiao.mp4");
    		videoView.setVideoPath(file.getPath());
    	}
    	@Override
    	public void onClick(View v) {
    		switch(v.getId()) {
    		case R.id.play_vieo:
    			if(!videoView.isPlaying()) {
    				videoView.start();
    			}
    			break;
    		case R.id.pause_vieo:
    			if(videoView.isPlaying()) {
    				videoView.pause();
    			}
    			break;
    		case R.id.replay:
    			if(videoView.isPlaying()) {
    				videoView.resume();
    			}
    			break;
    		}
    	}
    	public void onDestroy() {
    		super.onDestroy();
    		if(videoView!=null) {
    			videoView.suspend();
    		}
    	}
    }
  • 相关阅读:
    树的直径教学思路
    dfs序3树上差分
    DFS序与欧拉序的区别
    DFS序2
    树的重心教学思路
    loadrunner11并发注册码
    JPA 添加 converter
    银行信贷账户管理任务
    《如何启动黄金圈思维》笔记
    《野蛮进化》笔记
  • 原文地址:https://www.cnblogs.com/MrQlyn/p/10236334.html
Copyright © 2020-2023  润新知