Android first line of code - Chapter 8 multimedia

Posted by dave_biscuits on Sat, 25 Dec 2021 23:24:17 +0100

Use notification

First, a NotificationManager is needed to manage notifications, which can be obtained by calling the getsystem service () method of Context. The getSystemService() method receives a string parameter to determine which service to obtain from the system. Here we pass in Context NOTIFICATION_ Service is enough.

Run the program on your phone

Note: notificationcompat Builder (mainactivity. This,) deprecated, using notificationcompat Builder(MainActivity.this,“my_channel_01”)

  • The setContentTitle() method is used to specify the title content of the notification, which can be seen by pulling down the system status bar.
  • The setContentText() method is used to specify the body content of the notification, which can be seen by pulling down the system status bar.
  • The setWhen() method is used to specify the time when the notification is created, in milliseconds. When the system status bar is pulled down, the time specified here will be displayed on the corresponding notification.
  • The setSmallIcon() method is used to set the small icon of the notification. Note that you can only use the image of the pure alpha layer. The small icon will be displayed on the system status bar.
  • The setLargeIcon() method is used to set the large icon of the notification. When you pull down the system status bar, you can see the set large icon.

After the above work is completed, you only need to call the notify() method of NotificationManager to display the Notification. The notify() method receives two parameters. The first parameter is id. make sure that the id specified for each Notification is different. The second parameter is the Notification object. Here, we can directly pass in the Notification object we just created.

MainActivity.java

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button sendNotice = 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);
                //Create a Notification object using the Builder constructor of the NotificationCompat class
                Notification notification = new NotificationCompat.Builder(MainActivity.this,"my_channel_01")
                        //Specifies the title of the notification
                        .setContentTitle("This is content title")
                        //Specifies the body of the notification
                        .setContentText("This is context text")
                        //Specifies the time, in milliseconds, when the notification was created
                        .setWhen(System.currentTimeMillis())
                        //Set small icons for notifications
                        .setSmallIcon(R.mipmap.ic_launcher)
                        //Large icon for facility notification
                        .setLargeIcon(BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher))
                        .build();
                //Call notify() of NotificationManager to display the Notification. The first parameter is id. to ensure that the id of each Notification is different, the second parameter is the Notification object
                manager.notify(1,notification);
                break;
            default:
                break;
        }
    }
}

activity_main.xml

<Button
        android:id="@+id/send_notice"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Send notice"
        android:textAllCaps="false"/>

PendingIntent: deferred Intent

Several static methods are provided to obtain the instance of PendingIntent. You can choose whether to use getActivity() method, getBroadcast() method or getService() method. The parameters received by these methods are the same. The first parameter is still Context, and the second parameter is generally not used, usually passing in 0. The third parameter is an Intent object through which we can construct the "intention" of PendingIntent. The fourth parameter is used to determine the behavior of PendingIntent, including FLAG_ONESHOT,FLAG_NO_CREATE,FLAG_CANCEL_CURRENT and flag_ UPDATE_ The four values of current are optional. Usually, this parameter can be passed in as 0.

@Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.send_notice:
                Intent intent = new Intent(MainActivity.this,NotificationActivity.class);
                PendingIntent pi= PendingIntent.getActivity(this,0,intent,0);
                NotificationManager manager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
                //Create a Notification object using the Builder constructor of the NotificationCompat class
                Notification notification = new NotificationCompat.Builder(MainActivity.this,"my_channel_01")
                        //Specifies the title of the notification
                        .setContentTitle("This is content title")
                        //Specifies the body of the notification
                        .setContentText("This is context text")
                        //Specifies the time, in milliseconds, when the notification was created
                        .setWhen(System.currentTimeMillis())
                        //Set small icons for notifications
                        .setSmallIcon(R.mipmap.ic_launcher)
                        //Large icon for facility notification
                        .setLargeIcon(BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher))
                        //Construct a delayed intention through PendingIntent
                        .setContentIntent(pi)
                        .build();
                //Call notify() of NotificationManager to display the Notification. The first parameter is id. to ensure that the id of each Notification is different, the second parameter is the Notification object
                manager.notify(1,notification);
                break;
            default:
                break;
        }
    }

Delete notification icon after reading

  1. First: in notificationcompat A setAutoCancel() method is concatenated after builder()
.setAutoCancel(true).build();
  1. The second is to explicitly call the cancel() of NotificationManager to cancel
    Note: cancel(int i) has been deprecated, and it is invalid to use cancel("TAG", 1)
	NotificationManager manager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
	manager.cancel("TAG",1);

Advanced tips for notification

  • setSound() method: play a piece of audio when sending a notification. It receives a URI parameter, so when specifying an audio file, you need to obtain the URI corresponding to the audio file first. There are many audio files in the / system / mediaaudio / ringtones directory of each mobile phone. We can choose any one of them
  • setVibrate(): vibrate the phone. It is a long integer array, which is used to set the static and vibration time of the mobile phone, in milliseconds. A value with a subscript of 0 indicates the static time of the mobile phone, a value with a subscript of 1 indicates the vibration time of the mobile phone, a value with a subscript of 2 indicates the static time of the mobile phone, and so on. In addition, it has to be on Android manifest Add the declaration < uses permission Android: name = "Android. Permission. Vibrate" / > in the XML file
  • setLights(): sets the information led. Three parameters are received. The first parameter is used to specify the color of the LED lamp, the second parameter is used to specify the duration of the LED lamp on, in milliseconds, and the third parameter is used to specify the duration of the LED lamp off, also in milliseconds.
  • setDefaults() uses the default effect of notifications
//Set notification ringtone
.setSound(Uri.fromFile(new File("*/system/media/audio/ringtones/luna.ogg")))
//Set the vibration of the message
.setVibrate(new long[]{0,1000,1000,1000,1000})
//Set LED lights
.setLights(Color.BLUE,1000,1000)
//default setting
.setDefaults(NotificationCompat.DEFAULT_ALL)
.build();

Advanced features for notifications

  • setStyle(): allows you to build rich text notification content. This method receives a notificationcompat Stytle parameter But if the number of words is too long, the following information will be omitted with.
//Set the display information of the notification box
...
.setContentText("Learn how to build notifications,send and sync data, and use voice actions. Get the official Android IDE and developer tools to buildapps for Android.")
...

If you want to display a long piece of text:

//Set the display information of the notification box (not omitted)
.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."))
  • setPriority(): sets the importance of this notification. There are five constant values in total, which can be selected: PRIORITY_DEFAULT indicates the importance of default, which is the same as not setting; PRIORITY_MIN indicates the lowest importance. The system may display this notification only in specific scenarios, such as when the user drops down the status bar; PRIORITY_LOW indicates low importance. The system may reduce such notifications or change their display order to rank them after more important notifications; PRIORITY_HIGH indicates a high degree of importance. The system may enlarge such notices, or change the display order to place them in the front position; PRIORITY_MAX indicates the highest importance. Such notification messages must be immediately visible to users, and even require users to respond.
//Set importance
.setPriority(NotificationCompat.PRIORITY_MAX)

Call cameras and albums

Note: FileProvider will be used after 6.0. It is a special content provider, which improves the security of the application.

package com.example.cameraalbumtest;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.FileProvider;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

import java.io.File;
import java.io.FileNotFoundException;

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);
        Button takePhoto = findViewById(R.id.take_photo);
        picture = findViewById(R.id.picture);
        takePhoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //Create a File object to store the captured pictures
                File outputImage = new File(getExternalCacheDir(),"output_image.jpg");
                try{
                    //Determine whether it already exists
                    if(outputImage.exists()){
                        outputImage.delete();
                    }
                    outputImage.createNewFile();
                }catch(Exception e){
                    e.printStackTrace();
                }
                //Convert file to Uri object
                if(Build.VERSION.SDK_INT >=  24){
                    imageUri = FileProvider.getUriForFile(MainActivity.this,"com.example.cameraalbumtest.fileprovider",outputImage);
                }else{
                    imageUri = Uri.fromFile(outputImage);

                }
                //Start camera program
                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) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case TAKE_PHOTO:
                if (resultCode == RESULT_OK) {
                    try {
                        //Display the taken photos
                        Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri));
                        picture.setImageBitmap(bitmap);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                break;
            default:
                break;
        }

    }
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <Button
        android:id="@+id/take_photo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Take Photo"
        android:textAllCaps="false"/>
    
    <ImageView
        android:id="@+id/picture"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"/>

</LinearLayout>
package="com.example.cameraalbumtest">
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    ...
     <provider
            android:authorities="com.example.cameraalbumtest.fileprovider"
            android:name="androidx.core.content.FileProvider"
            android:exported="false"
            android:grantUriPermissions="true">

            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/file_paths"/>
        </provider>
    </application>
    ...

Select pictures from album

package com.example.cameraalbumtest;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.ContentUris;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.IInterface;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import java.io.File;
import java.io.FileNotFoundException;

public class MainActivity extends AppCompatActivity {

    public static final int TAKE_PHOTO = 1;

    public static final int CHOOSE_PHOTO = 2;

    private ImageView picture;

    private Uri imageUri;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button takePhoto = findViewById(R.id.take_photo);
        Button chooseFromAlbum = findViewById(R.id.choose_from_album);
        picture = findViewById(R.id.picture);
        takePhoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //Create a File object to store the captured pictures
                File outputImage = new File(getExternalCacheDir(), "output_image.jpg");
                try {
                    //Determine whether it already exists
                    if (outputImage.exists()) {
                        outputImage.delete();
                    }
                    outputImage.createNewFile();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                //Convert file to Uri object
                if (Build.VERSION.SDK_INT >= 24) {
                    imageUri = FileProvider.getUriForFile(MainActivity.this, "com.example.cameraalbumtest.fileprovider", outputImage);
                } else {
                    imageUri = Uri.fromFile(outputImage);

                }
                //Start camera program
                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/*");
        //The following request code is a unique value
        startActivityForResult(intent, CHOOSE_PHOTO);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case TAKE_PHOTO:
                if (resultCode == RESULT_OK) {
                    try {
                        //Display the taken photos
                        Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri));
                        picture.setImageBitmap(bitmap);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                break;
            case CHOOSE_PHOTO:
                if (resultCode == RESULT_OK) {
                    //Judge the mobile phone system version number
                    if (Build.VERSION.SDK_INT >= 19) {
                        handleImageOnKitKat(data);
                    } else {
                        handleImageBeforeKitKat(data);
                    }
                }
            default:
                break;
        }

    }

    private void handleImageBeforeKitKat(Intent data) {
        Uri uri = data.getData();
        String imagePath = getImagePath(uri,null);
        displayImage(imagePath);
    }

    //Resolve encapsulated Uri
    private void handleImageOnKitKat(Intent data) {
        String imagePath = null;
        Uri uri = data.getData();
        //The document type is returned
        if (DocumentsContract.isDocumentUri(this, uri)) {
            //Take out the id for processing
            String docId = DocumentsContract.getDocumentId(uri);
            //The authority of Uri is media
            if ("com.android.providers.media.documents".equals(uri.getAuthority())) {
                String id = docId.split(":")[1];
                String selection = MediaStore.Images.Media._ID + "=" + id;
                //Build new Uri and conditional statements
                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())){
            //If the content form is Uri, the normal method is used
            imagePath = getImagePath(uri,null);
        }else if("file".equalsIgnoreCase(uri.getScheme())){
            //If it is a Uri of file type, you can directly obtain the image path
            imagePath = uri.getPath();
        }
        displayImage(imagePath);
    }

    private void displayImage(String imagePath) {
        if(imagePath != null){
            Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
            picture.setImageBitmap(bitmap);
        }else{
            Toast.makeText(this, "filed to get image", Toast.LENGTH_SHORT).show();
        }
    }

    @SuppressLint("Range")
    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;
    }


    @Override
    public void onRequestPermissionsResult(int requestCode,String[] permissions,int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode){
            case 1:
                if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
                    openAlbum();
                }else{
                    Toast.makeText(this, "You have refused authorization", Toast.LENGTH_SHORT).show();
                }
                break;
            default:
                break;
        }
    }
}

Play multimedia files

 package="com.example.playaudiotest">
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
package com.example.playaudiotest;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.content.pm.PackageManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.Button;

import java.io.File;

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 = findViewById(R.id.play);
        Button pause = findViewById(R.id.pause);
        Button stop = 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");
            //Preparation before playing
            mediaPlayer.setDataSource(file.getPath());
            mediaPlayer.prepare();
        }catch(Exception e){
            e.printStackTrace();
        }
    }

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

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(mediaPlayer!=null){
            mediaPlayer.stop();
            //It is recommended to call release() once the MediaPlayer object is no longer used, so that the resources used by the internal player engine associated with the MediaPlayer object can be released immediately.
            mediaPlayer.release();
        }
    }
}

Play video

<?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">

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

        <Button
            android:id="@+id/play"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="start"/>
        
        <Button
            android:id="@+id/pause"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="suspend"/>
        
        <Button
            android:id="@+id/replay"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="replay"/>
    </LinearLayout>
    
    <VideoView
        android:id="@+id/video_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

</LinearLayout>
package com.example.playvideotest;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
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 = findViewById(R.id.video_view);
        Button play = findViewById(R.id.play);
        Button pause = findViewById(R.id.pause);
        Button replay = 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(),"DCIM/Camera/VID_20210811_112704.mp4");
        Toast.makeText(this, "Found it", Toast.LENGTH_SHORT).show();
        videoView.setVideoPath(file.getPath());
        Log.d("TAG",file.getPath());
    }

    @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();//Replay
                }
            default:
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(videoView!=null){
            videoView.suspend();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode){
            case 1:
                if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
                    initVideoPath();
                }else {
                    Toast.makeText(this, "Denial of permission will prevent the program from being used", Toast.LENGTH_SHORT).show();
                    finish();
                }
                break;
            default:
                break;
        }
    }
}

Topics: Java Android Android Studio