Android基础知识——运用手机多媒体

1.将程序运行到手机上

下面我们讲到的一些代码,可能只有把程序运行到真机上,才会看到效果,教程

2.使用通知

通知是Android系统中比较有特色的一个功能,当某个应用程序希望向用户发出一些提示信息,而该应用程序又不在前台运行时,就可以借助通知来实现。

2.1通知的基本用法

使用步骤:

1.调用getSupportService(NOTIFICATION_SERVICE)方法获取NotificationManager实例。
2.获取NotificationChannel实例。
3.调用manager.createNotificationChannel(channel)方法,创建NotificationChannel。
4.获取Notification实例,再给其设置一些属性。
5.调用managermanager.notify(1(该通知的id),notification)方法,发送通知。

示例;

public class MainActivity extends AppCompatActivity {
    
    

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button button=(Button) findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
    
    
            @RequiresApi(api = Build.VERSION_CODES.O)
            @Override
            public void onClick(View view) {
    
    
                NotificationManager manager= (NotificationManager) getSystemService(NOTIFICATION_SERVICE);//步骤一
                NotificationChannel channel=new NotificationChannel("1","MY_CHANNEL", NotificationManager.IMPORTANCE_DEFAULT);//步骤二,第一个参数是该channel的id,第二个参数是该channel的名字,第三个参数是通知的优先级
                manager.createNotificationChannel(channel);//步骤三
                Notification notification=new NotificationCompat.Builder(MainActivity.this,"1")//步骤四,注意第二个参数是关联channel的id
                        .setContentTitle("This is title")//设置通知的title
                        .setContentText("This is text")//设置通知的text
                        .setWhen(System.currentTimeMillis())//设置通知上显示的发送时间
                        .setSmallIcon(R.mipmap.ic_launcher)//设置通知的小图标
                        .setLargeIcon(BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher))//设置通知的大图标
                        .build();
                manager.notify(1,notification);//发送通知
            }
        });
    }
}

2.2通知的进阶技巧

在上节中我们只是简单的发送了一个通知,在本节中我们就来给通知设置上一些进阶性的功能。

给通知设置点击事件:

示例:

Intent intent=new Intent(MainActivity.this,MainActivity2.class);
PendingIntent pendingIntent=PendingIntent.getActivity(MainActivity.this,0,intent,0);
......
Notification notification=new NotificationCompat.Builder(MainActivity.this,"1")
        .setContentTitle("This is title")
        .setContentText("This is text")
        .setWhen(System.currentTimeMillis())
        .setSmallIcon(R.mipmap.ic_launcher)
        .setLargeIcon(BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher))
        .setContentIntent(pendingIntent)//给通知设置点击事件
        .setAutoCancel(true)//当通知被点击之后,自动取消
        .build();

给通知设置提示音:

首先在res目录下新建一个raw文件夹,在其中存放一段mp3

示例:

Intent intent=new Intent(MainActivity.this,MainActivity2.class);
PendingIntent pendingIntent= PendingIntent.getActivity(MainActivity.this,0,intent,0);
NotificationManager manager= (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
NotificationChannel channel=new NotificationChannel("2","MY_CHANNEL", NotificationManager.IMPORTANCE_DEFAULT);
channel.setSound(Uri.parse("android.resource://"+MainActivity.this.getPackageName()+"/raw/"+R.raw.music),null);//给通知设置提示音
manager.createNotificationChannel(channel);
Notification notification=new NotificationCompat.Builder(MainActivity.this,"2")
        .setContentTitle("This is title")
        .setContentText("This is text")
        .setWhen(System.currentTimeMillis())
        .setSmallIcon(R.mipmap.ic_launcher)
        .setLargeIcon(BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher))
        .setContentIntent(pendingIntent)
        .setAutoCancel(true)
        .build();
manager.notify(1,notification);

给通知设置震动:

示例:

Intent intent=new Intent(MainActivity.this,MainActivity2.class);
PendingIntent pendingIntent= PendingIntent.getActivity(MainActivity.this,0,intent,0);
NotificationManager manager= (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
NotificationChannel channel=new NotificationChannel("3","MY_CHANNEL", NotificationManager.IMPORTANCE_DEFAULT);
channel.setSound(Uri.parse("android.resource://"+MainActivity.this.getPackageName()+"/raw/"+R.raw.music),null);
channel.setVibrationPattern(new long[]{
    
    0,1000,1000,1000});//给通知设置震动,该震动为通知到来时先震动1s,再静止1s,再震动1s。
manager.createNotificationChannel(channel);
Notification notification=new NotificationCompat.Builder(MainActivity.this,"3")
        .setContentTitle("This is title")
        .setContentText("This is text")
        .setWhen(System.currentTimeMillis())
        .setSmallIcon(R.mipmap.ic_launcher)
        .setLargeIcon(BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher))
        .setContentIntent(pendingIntent)
        .setAutoCancel(true)
        .build();
manager.notify(1,notification);

2.3通知的高级功能

在本节中我们就来学习给通知设置更多的属性。

设置长文字:

示例:

Notification notification=new NotificationCompat.Builder(MainActivity.this,"4")
        .setContentTitle("This is title")
        .setStyle(new NotificationCompat.BigTextStyle().bigText("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"))//给通知设置长文字
        .setWhen(System.currentTimeMillis())
        .setSmallIcon(R.mipmap.ic_launcher)
        .setLargeIcon(BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher))
        .setContentIntent(pendingIntent)
        .setAutoCancel(true)
        .build();

设置图片:

示例:

Notification notification=new NotificationCompat.Builder(MainActivity.this,"4")
        .setContentTitle("This is title")
        .setStyle(new NotificationCompat.BigPictureStyle().bigPicture(BitmapFactory.decodeResource(getResources(),R.drawable.apple))
        .setWhen(System.currentTimeMillis())
        .setSmallIcon(R.mipmap.ic_launcher)
        .setLargeIcon(BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher))//给通知设置图片
        .setContentIntent(pendingIntent)
        .setAutoCancel(true)
        .build();

设置通知的优先级:

示例:

NotificationChannel channel=new NotificationChannel("5","MY_CHANNEL", NotificationManager.IMPORTANCE_HIGH);//第三个参数就是通知的优先级

通知的优先级共分5种:

  • NotificationManager.IMPORTANCE_NONE
  • NotificationManager.IMPORTANCE_MIN
  • NotificationManager.IMPORTANCE_LOW
  • NotificationManager.IMPORTANCE_DEFAULT
  • NotificationManager.IMPORTANCE_HIGH(该模式下通知将变为横幅)

3.调用摄像头

使用步骤:

1.创建存放照片的文件。
2.获取文件的uri。
3.打开相机。
4.将拍摄得到的照片转换成位图的形式,并显示出来。
5.声明权限,注册内容提供器等。

示例:

public class MainActivity extends AppCompatActivity  {
    
    
    private Uri uri;
    private ImageView imageView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        imageView=(ImageView) findViewById(R.id.image_view);
        Button button=(Button) findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
    
    
            @Override
            public void onClick(View view) {
    
    
          	    //步骤一
                File file=new File(getExternalCacheDir(),"output_image.jpg");
                try {
    
    
                    if(file.exists()){
    
    
                        file.delete();
                    }
                    file.createNewFile();
                } catch (IOException e) {
    
    
                    e.printStackTrace();
                }
                //步骤二
                if(Build.VERSION.SDK_INT>=24){
    
    //在android7.0之后不允许直接获取文件的真实路径,需要借助内容提供器来获取文件的真实路径,且借助内容提供器可以避免在代码中申请"android.permission.READ_EXTERNAL_STORAGE" 权限
                    uri=FileProvider.getUriForFile(MainActivity.this,"com.example.temp02.fileprovider",file);
                }else {
    
    
                    uri=Uri.fromFile(file);
                }
				//步骤三
                Intent intent=new Intent("android.media.action.IMAGE_CAPTURE");
                intent.putExtra(MediaStore.EXTRA_OUTPUT,uri);
                startActivityForResult(intent,1);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    
    
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode){
    
    
            case 1:
                if(resultCode==RESULT_OK){
    
    
                    try {
    
    
                    	//步骤四
                        Bitmap bitmap=BitmapFactory.decodeStream(getContentResolver().openInputStream(uri));
                        imageView.setImageBitmap(bitmap);
                    } catch (FileNotFoundException e) {
    
    
                        e.printStackTrace();
                    }
                }
                break;
            default:
        }
    }
}
//步骤五

//声明权限
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
//注册内容提供器
<provider
    android:authorities="com.example.temp02.fileprovider"
    android:name="androidx.core.content.FileProvider"//与步骤二中getUriForFile()方法的第二个参数保持一致
    android:exported="false"
    android:grantUriPermissions="true">
    <meta-data
        android:name="android.support.FILE_PROVIDER_PATHS"
        android:resource="@xml/file_paths" />//指定Uri的共享路径
</provider>
//xml文件夹下的file_paths文件
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path
        name="my_images"//该内容可以随意填写
        path="." />
</paths>

4.播放多媒体文件

4.1播放音频

首先新建一个assets文件夹,并在其中放上想要播放的资源。

使用步骤:
1.获取MediaPlayer实例。
2.调用setDataSource()方法给MediaPlayer设置待播放的资源。
3.调用prepare()方法准备开始播放。
4.可以调用MediaPlayer中的一些API对播放的资源进行控制。
5.最后要释放掉MediaPlayer中的资源。

示例:

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);
        try {
    
    
        	//步骤二
            AssetManager manager=getResources().getAssets();
            AssetFileDescriptor descriptor=manager.openFd("music.mp3");
            mediaPlayer.setDataSource(descriptor.getFileDescriptor(),descriptor.getStartOffset(),descriptor.getStartOffset());
            mediaPlayer.prepare();//步骤三
        } catch (IOException e) {
    
    
            e.printStackTrace();
        }
    }

    @Override
    public void onClick(View view) {
    
    
        switch (view.getId()){
    
    
        	//步骤四
            case R.id.play:
                if(!mediaPlayer.isPlaying()){
    
    
                    mediaPlayer.start();
                }
                Toast.makeText(MainActivity.this,"play",Toast.LENGTH_SHORT).show();
                break;
            case R.id.pause:
                if(mediaPlayer.isPlaying()){
    
    
                    mediaPlayer.pause();
                }
                break;
            case R.id.stop:
                if(mediaPlayer.isPlaying()){
    
    
                    mediaPlayer.stop();
                    try {
    
    
                        mediaPlayer.prepare();
                    } catch (IOException e) {
    
    
                        e.printStackTrace();
                    }
                }
                break;
            default:
                break;
        }
    }
    
    @Override
    protected void onDestroy() {
    
    
        super.onDestroy();
        mediaPlayer.release();//步骤五
    }
}

4.2播放视频

首先要先建一个raw文件夹,并在其中放上想要播放的资源

使用步骤:

1.在布局中加入VideoView布局。
2.获取VideoView的实例。
3.给VideoView设置待播放的资源。
4.可以调用VideoView中的一些API对播放的资源进行控制。
5.最后要释放掉VieoView中的资源。

示例:

//步骤一
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <Button
            android:id="@+id/play"
            android:text="Play"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content" />

        <Button
            android:id="@+id/pause"
            android:text="Pause"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content" />

        <Button
            android:id="@+id/replay"
            android:text="Replay"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content" />

    </LinearLayout>

    <VideoView
        android:id="@+id/video_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</LinearLayout>

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);
        videoView.setVideoPath(String.valueOf(Uri.parse("android.resource://"+ MainActivity.this.getPackageName()+"/raw/"+R.raw.temp)));//步骤三
    }

    @Override
    public void onClick(View view) {
    
    
        switch (view.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;
            default:
                break;
        }
    }

    @Override
    protected void onDestroy() {
    
    
        super.onDestroy();
        videoView.suspend();//步骤五
    }
}

猜你喜欢

转载自blog.csdn.net/ABded/article/details/108540060
今日推荐