第八章 运用手机多媒体
8.1 将程序运行到手机上
8.2 通知
8.2.1 通知的基本用法
需要用NotificationManager来对通知进行管理,调用Context的getSystemService()方法,传入Context.NOTIFICATION_SERVICE获得。
NotificationManager manager = (NotificationManager)
getSystemService(Context.NOTIFICATION_SERVICE);
接下来要用Builder构造器来创建Notification对象,使用support-v4库中提供了一个NotificationCompat类
Notification notification = new NotificationCompat.Builder(context).build() .setContentTitle("This is content title") //指定通知的标题内容 .setContentText("This is content text") //指定通知的正文内容 .setWhen(System.currentTimeMillis()) //指定通知被创建的时间,以毫秒为单位 .setSmallIcon(R.drawable.small_icon) //设置通知的小图标 .setLargeIcon(BitmapFactory.decodeResource(getResource(), R.drawable.large_icon)) //设置通知的大图标 .build();
调用notify()方法让通知显示出来,接收两个参数,第一个为id,所以确保每个通知的id都不同, 第二个参数为Notification对象,即为
manager.notify(1,notification)
1.具体实现:
新建项目NotificationTest
修改activity_main中的代码添加Button用于添加显示通知的动作
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center_horizontal" tools:context="com.example.song.notification.MainActivity"> <Button android:id="@+id/send_notice" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Send notice"/> </LinearLayout>
修改MainActivity中的代码
import android.app.Notification; import android.app.NotificationManager; import android.graphics.BitmapFactory; import android.support.v4.app.NotificationCompat; import android.support.v7.app.AppCompatActivity; import android.support.v4.app.NotificationManagerCompat; import android.os.Bundle; import android.view.View; import android.widget.Button; public class MainActivity extends AppCompatActivity implements View.OnClickListener{ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button sendNotice = (Button)findViewById(R.id.send_notice); sendNotice.setOnClickListener(this); } @Override public void onClick(View view) { switch(view.getId()){ case R.id.send_notice: NotificationManager manager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE); Notification notification = new NotificationCompat.Builder(this) .setContentTitle("This is content file") .setContentText("This is content text") .setWhen(System.currentTimeMillis()) .setSmallIcon(R.mipmap.ic_launcher) .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher)) .build(); manager.notify(1, notification); break; default: break; } } }
运行程序:
2.PendingIntent:延迟执行的Intent
提供三个静态方法,getActivity()方法,getBroadcast()方法,getService()方法,接收参数有四个,第一个为Context,第二个参数一般用不到,传入0,第三个参数为Intent对象,第四个参数用于确定PendingIntent的行为,有FLAG_ONE_SHOT、FLAG_NO_CREATE、FLAG_CANCEL_CURRENT、FLAG_UPDATE_CURRENT四种值。
通过PendingIntent当点击通知时,跳转到其他活动
新建活动NotificationActivity
修改布局文件
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="This is notification layout" android:textSize="24dp" android:layout_gravity="center"/> </LinearLayout>
修改MainActivity中的代码
@Override public void onClick(View view) { switch(view.getId()){ case R.id.send_notice: Intent intent = new Intent(this, NotificationActivity.class); PendingIntent pi = PendingIntent.getActivity(this, 0, intent, 0); NotificationManager manager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE); Notification notification = new NotificationCompat.Builder(this) .setContentTitle("This is content file") .setContentText("This is content text") .setWhen(System.currentTimeMillis()) .setContentIntent(pi) .setSmallIcon(R.mipmap.ic_launcher) .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher)) .build(); manager.notify(1, notification); break; default: break; } }
当点击通知时,即可跳转到NotificationActivity
但此时系统状态的通知图标仍存在,有两种方法进行取消
1)Builder连缀一个setAutoCancel方法
.setAutoCancel(true)
2)
public class NotificationActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.notification_layout); NotificationManager manager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE); manager.cancel(1); } }
cancel()方法中传入的1为通知的id
8.2.2 通知的进阶技巧
1.添加声音
.setSound(Uri.fromFile(new File(" ")))
2.添加振动(比如通知到来时立刻振动1秒,静止1秒,再振动1秒)
.setVibrate(new long[]{0, 1000, 1000, 1000})
同时要添加权限
<uses-permission android:name="android.permission.VIBRATE"/>
3.控制LED灯显示(绿灯一闪一闪的效果)
.setLights(Color.GREEN, 1000, 1000)
4.直接使用默认效果
.setDefaults(NotificationCompat.DEFAULT_ALL)
8.2.3 通知的高级功能
1.通知内容比较短时
直接使用.setContentText
2.通知内容比较长时
.setStyle(new NotificationCompat.BigTextStyle().bigText("Learn how to build notifications, send and sync data, and use " +
"voice actions.Get the official Android IDE and developer tools to build apps for Android"))
3.大图片
.setStyle(new NotificationCompat.BigPictureStyle().bigPicture (BitmapFactory.decodeResource(getResources(),R.drawable.gareen)))
4.设置重要程度
setPriority()
.setPriority(NotificationCompat.PRIORITY_MAX)
8.3 调用摄像头和相册
8.3.1 调用摄像头
新建项目CameraAlbumTest
1.修改activity_main中的代码
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context="com.example.song.cameraalbumtest.MainActivity"> <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>
Button用于拍照,ImageView用于将照片显示出来
2.修改MainActivity中的方法
public class MainActivity extends AppCompatActivity { public static final int TAKE_PHOTO = 1; private ImageView picture; private Uri imageUri; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); picture = (ImageView)findViewById(R.id.picture); Button takePhoto = (Button)findViewById(R.id.take_photo); takePhoto.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { File outputImage = new File(getExternalCacheDir(), "output_image.jpg"); try{ if(outputImage.exists()){ outputImage.delete(); } outputImage.createNewFile(); }catch (IOException e){ e.printStackTrace(); } if(Build.VERSION.SDK_INT >= 24){ imageUri = FileProvider.getUriForFile(MainActivity.this, "com.example.song.cameraalbumtest.fileprovider",outputImage); }else{ imageUri = Uri.fromFile(outputImage); } Intent intent = new Intent("android.media.action.IMAGE_CAPTURE"); intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri); startActivityForResult(intent, TAKE_PHOTO); } }); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { switch(requestCode){ case TAKE_PHOTO: if(resultCode == RESULT_OK){ try{ //将拍摄的照片显示出来 Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri)); picture.setImageBitmap(bitmap); }catch(FileNotFoundException e){ e.printStackTrace(); } } break; default: break; } } }
在AndroidManifest.xml中对内容提供器进行注册
<provider android:authorities="com.example.song.cameraalbumtest.fileprovider" android:name="android.support.v4.content.FileProvider" android:exported="false" android:grantUriPermissions="true"> <meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/file_paths"/> </provider>
同时声明权限
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
8.3.2 从相册中选择照片
public class MainActivity extends AppCompatActivity { public static final int TAKE_PHOTO = 1; private ImageView picture; private Uri imageUri; public static final int CHOOSE_PHOTO = 2; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); picture = (ImageView)findViewById(R.id.picture); Button takePhoto = (Button)findViewById(R.id.take_photo); Button chooseFromAlbum = (Button)findViewById(R.id.choose_from_album); takePhoto.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { File outputImage = new File(getExternalCacheDir(), "output_image.jpg"); try{ if(outputImage.exists()){ outputImage.delete(); } outputImage.createNewFile(); }catch (IOException e){ e.printStackTrace(); } if(Build.VERSION.SDK_INT >= 24){ imageUri = FileProvider.getUriForFile(MainActivity.this, "com.example.song.cameraalbumtest.fileprovider",outputImage); }else{ imageUri = Uri.fromFile(outputImage); } Intent intent = new Intent("android.media.action.IMAGE_CAPTURE"); intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri); startActivityForResult(intent, TAKE_PHOTO); } }); chooseFromAlbum.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if(ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){ ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1); }else{ openAlbum(); } } }); } private void openAlbum(){ Intent intent = new Intent("android.intent.action.GET_CONTENT"); intent.setType("image/*"); startActivityForResult(intent, CHOOSE_PHOTO); } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { switch(requestCode){ case 1: if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){ openAlbum(); }else { Toast.makeText(this, "You denied the permission", Toast.LENGTH_SHORT).show(); } break; default: } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { switch(requestCode){ case TAKE_PHOTO: if(resultCode == RESULT_OK){ try{ //将拍摄的照片显示出来 Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri)); picture.setImageBitmap(bitmap); }catch(FileNotFoundException e){ e.printStackTrace(); } } break; case CHOOSE_PHOTO: if(resultCode == RESULT_OK){ if(Build.VERSION.SDK_INT >= 19){ //4.4及以上系统使用这个方法处理图片 handleImageOnKitkat(data); }else{ //4.4以下系统使用这个方法处理图片 handleImageforeKitkat(data); } } break; default: break; } } private void handleImageOnKitkat(Intent data){ String imagePath = null; Uri uri = data.getData(); 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.provides.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(); } displayImage(imagePath); } private void handleImageforeKitkat(Intent data){ Uri uri = data.getData(); String imagePath = getImagePath(uri, null); displayImage(imagePath); } private String getImagePath(Uri uri, String selection){ String path = null; Cursor cursor = getContentResolver().query(uri, 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 displayImage(String imagePath){ if(imagePath != null){ Bitmap bitmap = BitmapFactory.decodeFile(imagePath); picture.setImageBitmap(bitmap); }else{ Toast.makeText(this, "failed to get Image", Toast.LENGTH_SHORT).show(); } } }
8.4 播放多媒体文件
8.4.1 播放音频
在Android中播放音频文件一般都是使用MediaPlayer类来实现的。
MediaPlayer的工作流程:首先需要创建出一个MediaPlayer对象,然后调用setDataSource()方法来设置音频文件的路径,再调用prepare()方法使MediaPlayer进入到准备状态,接下来调用start()方法就可以开始播放音频,调用pause()方法就会暂停播放,调用reset()方法就会停止播放。
新建PlayAudioTest项目,修改activity_main中的代码,放置三个按钮用于进行播放、暂停和停止操作
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity"> <Button android:id="@+id/play" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="PLAY" /> <Button android:id="@+id/pause" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="PAUSE" /> <Button android:id="@+id/stop" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="STOP" /> </LinearLayout>
修改MainActivity中的代码
public class MainActivity extends AppCompatActivity implements View.OnClickListener { private MediaPlayer mediaPlayer = new MediaPlayer(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button play = (Button)findViewById(R.id.play); Button pause = (Button)findViewById(R.id.pause); Button stop = (Button)findViewById(R.id.stop); play.setOnClickListener(this); pause.setOnClickListener(this); stop.setOnClickListener(this); if(ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission. WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){ ActivityCompat.requestPermissions(MainActivity.this, new String[]{ Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1); }else{ initMediaPlayer(); } } private void initMediaPlayer(){ try{ File file = new File(Environment.getExternalStorageDirectory(), "music.mp3"); mediaPlayer.setDataSource(file.getPath()); mediaPlayer.prepare(); }catch (Exception e){ e.printStackTrace(); } } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { switch (requestCode){ case 1: if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){ initMediaPlayer(); }else{ Toast.makeText(this,"拒绝权限将无法使用程序", Toast.LENGTH_SHORT).show(); finish(); } break; default: } } @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; } } @Override protected void onDestroy() { super.onDestroy(); if(mediaPlayer != null){ mediaPlayer.stop(); mediaPlayer.release(); } } }
添加权限
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
8.4.2 播放视频
新建项目PlayVideoTest
修改activity_main中的代码
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <Button android:id="@+id/play" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:text="Play" /> <Button android:id="@+id/pause" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:text="Pause" /> <Button android:id="@+id/replay" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:text="Stop" /> </LinearLayout> <VideoView android:id="@+id/video_view" android:layout_width="match_parent" android:layout_height="wrap_content" /> </LinearLayout>
修改MainActivity中的代码
import android.Manifest; import android.content.pm.PackageManager; import android.os.Environment; import android.support.annotation.NonNull; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.Toast; import android.widget.VideoView; import java.io.File; public class MainActivity extends AppCompatActivity implements View.OnClickListener{ private VideoView videoView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); videoView = (VideoView)findViewById(R.id.video_view); Button play = (Button)findViewById(R.id.play); Button pause = (Button)findViewById(R.id.pause); Button replay = (Button)findViewById(R.id.replay); play.setOnClickListener(this); pause.setOnClickListener(this); replay.setOnClickListener(this); if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest. permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){ ActivityCompat.requestPermissions(MainActivity.this, new String[]{ Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1); }else{ initVideoPath(); } } private void initVideoPath(){ File file = new File(Environment.getExternalStorageDirectory(),"movie.mp4"); videoView.setVideoPath(file.getPath()); } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { switch(requestCode){ case 1: if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){ initVideoPath(); }else { Toast.makeText(this, "拒绝权限将无法使用程序", Toast.LENGTH_SHORT).show(); finish(); } break; default: } } @Override public void onClick(View v) { switch(v.getId()){ case R.id.play: if(!videoView.isPlaying()){ videoView.start(); } break; case R.id.pause: if(videoView.isPlaying()){ videoView.pause(); } break; case R.id.replay: if(videoView.isPlaying()){ videoView.resume(); } break; } } @Override protected void onDestroy() { super.onDestroy(); if(videoView != null){ videoView.suspend(); } } }
添加权限
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>