Android Basics: DAY09 Multimedia programming

Source: Internet
Author: User
Tags gety prepare

DAY09 Multimedia Programming One, dialog box 1. OK Cancel dialog box
    • Create a Dialog builder object similar to Factory mode

      AlertDialog.Builder builder = new Builder(this);
    • Set the title and body

      builder.setTitle("警告");builder.setMessage("若练此功,必先自宫");
    • Set OK and Cancel buttons

      builder.setPositiveButton("现在自宫", new OnClickListener() {    @Override    public void onClick(DialogInterface dialog, int which) {        Toast.makeText(MainActivity.this, "恭喜你自宫成功,现在程序退出", 0).show();    }});builder.setNegativeButton("下次再说", new OnClickListener() {    @Override    public void onClick(DialogInterface dialog, int which) {        Toast.makeText(MainActivity.this, "若不自宫,一定不成功", 0).show();    }});
    • Using the Builder to create a dialog box object

      AlertDialog ad = builder.create();ad.show();
2. Single-selection dialog box
    • Create a dialog box object

      AlertDialog.Builder builder = new Builder(this);builder.setTitle("选择你的性别");
    • Define a radio option

      final String[] items = new String[]{        "男", "女", "其他"};// -1表示默认选择builder.setSingleChoiceItems(items, -1, new OnClickListener() {    // which表示点击的是哪一个选项    @Override    public void onClick(DialogInterface dialog, int which) {        Toast.makeText(MainActivity.this, "您选择了" + items[which], 0).show();        // 对话框消失        dialog.dismiss();    }});builder.show();
3. Multi-Select dialog box
  • The option to define multiple selections, because you can select multiple, so you need a Boolean array to record which options are selected

    AlertDialog.Builder builder = new Builder(this);builder.setTitle("请选择你认为最帅的人");final String[] items = new String[]{        "赵帅哥",        "赵师哥",        "赵老师",        "侃哥"};// true表示对应位置的选项被选了final boolean[] checkedItems = new boolean[]{        true,        false,        false,        false,};builder.setMultiChoiceItems(items, checkedItems, new OnMultiChoiceClickListener() {    // 点击某个选项,如果该选项之前没被选择,那么此时isChecked的值为true    @Override    public void onClick(DialogInterface dialog, int which, boolean isChecked) {        checkedItems[which] = isChecked;    }});builder.setPositiveButton("确定", new OnClickListener() {    @Override    public void onClick(DialogInterface dialog, int which) {        StringBuffer sb = new StringBuffer();        for(int i = 0;i < items.length; i++){            sb.append(checkedItems[i] ? items[i] + " " : "");        }        Toast.makeText(MainActivity.this, sb.toString(), 0).show();    }});builder.show();


Second, internationalization
    • String internationalization: Just create a new values folder for the corresponding language under the Res folder.
    • American English Environment: Values-en-rus
    • The Chinese environment is: Values-zh
    • Mainland Chinese Environment: VALUES-ZH-CN


Iii. Styles and Themes
    • Styles are defined in the same way as themes
    • Styles for components in a layout file
    • Topics for activity


Iv. Multimedia Programming 4.1 Calculation of computer picture size
    • Picture size = Total pixels of the picture * the size occupied by each pixel
    • Monochrome graphs: 1/8 bytes per pixel
    • 16 Color graphs: 1/2 bytes per pixel
    • 256 Color graphs: 1 bytes per pixel
    • 24-bit graph: 3 bytes per pixel
4.2 Loading large images into memory
    • The Android system uses ARGB to represent each pixel, with 4 bytes per pixel, so it's easy to memory overflow, so we need to scale the picture
4.3 Zooming on a picture
    • Get Screen width height

      Display dp = getWindowManager().getDefaultDisplay();int screenWidth = dp.getWidth();int screenHeight = dp.getHeight();
    • Get Picture Width height

      Options opts = new Options();// 请求图片属性但不申请内存opts.inJustDecodeBounds = true;BitmapFactory.decodeFile("sdcard/dog.jpg", opts);int imageWidth = opts.outWidth;int imageHeight = opts.outHeight;
    • The width of the picture, divided by the width of the screen, calculates a wide and high scale, and takes a larger value as the scale of the picture.

      int scale = 1;int scaleX = imageWidth / screenWidth;int scaleY = imageHeight / screenHeight;if(scaleX >= scaleY && scaleX > 1){    scale = scaleX;}else if(scaleY > scaleX && scaleY > 1){    scale = scaleY;}
    • Load pictures by scale

      // 设置缩放比例opts.inSampleSize = scale;// 为图片申请内存opts.inJustDecodeBounds = false;Bitmap bm = BitmapFactory.decodeFile("sdcard/dog.jpg", opts);iv.setImageBitmap(bm);
4.4 Creating a copy of a picture in memory
    • The directly loaded bitmap object is read-only and cannot be modified, and the image can only be modified in memory to create an identical bitmap copy, and then modify the copy

      // 加载原图Bitmap srcBm = BitmapFactory.decodeFile("sdcard/photo3.jpg");iv_src.setImageBitmap(srcBm);// 创建与原图大小一致的空白bitmapBitmap copyBm = Bitmap.createBitmap(srcBm.getWidth(), srcBm.getHeight(), srcBm.getConfig());// 定义画笔Paint paint = new Paint();// 把纸铺在画版上Canvas canvas = new Canvas(copyBm);// 把srcBm的内容绘制在copyBm上canvas.drawBitmap(srcBm, new Matrix(), paint);iv_copy.setImageBitmap(copyBm);
4.5 Special effects for image processing
    • First define a Matrix object

      Matrix mt = new Matrix();
    • Zoom effect

      // x轴缩放1倍,y轴缩放0.5倍mt.setScale(1, 0.5f);
    • Rotation effect

      // 以图片宽高的一半中心点为轴点,顺时旋转30度mt.setRotate(30, copyBm.getWidth() / 2, copyBm.getHeight() / 2);
    • Translation

      // x轴坐标+10,y轴坐标+20mt.setTranslate(10, 20);
    • Mirror

      // 把X坐标都变成负数mt.setScale(-1, 1);// 图片整体向右移mt.postTranslate(copyBm.getWidth(), 0);
    • Reflection

      // 把Y坐标都变成负数mt.setScale(1, -1);// 图片整体向下移mt.postTranslate(0, copyBm.getHeight());


V. Multimedia Case 5.1 drawing board

Function: Record the XY coordinates of user touch events, draw lines

  • Set the touch listener to ImageView, get the user's touch event, and learn the user's touch ImageView coordinates

    iv.setOnTouchListener(new OnTouchListener() {    @Override    public boolean onTouch(View v, MotionEvent event) {        switch (event.getAction()) {        // 触摸屏幕        case MotionEvent.ACTION_DOWN:            // 得到触摸屏幕时手指的坐标            startX = (int) event.getX();            startY = (int) event.getY();            break;        // 在屏幕上滑动        case MotionEvent.ACTION_MOVE:            // 用户滑动手指,坐标不断的改变,获取最新坐标            int newX = (int) event.getX();            int newY = (int) event.getY();            // 用上次onTouch方法得到的坐标和本次得到的坐标绘制直线            canvas.drawLine(startX, startY, newX, newY, paint);            iv.setImageBitmap(copyBm);            startX = newX;            startY = newY;            break;        }        return true;    }});
  • Brush effect, Bold brush

    paint.setStrokeWidth(8);
  • palette, changing brush color

    paint.setColor(Color.GREEN);
  • Save picture to SD card

    FileOutputStream fos = null;try {    fos = new FileOutputStream(new File("sdcard/dazuo.png"));} catch (FileNotFoundException e) {    e.printStackTrace();}// 保存图片copyBm.compress(CompressFormat.PNG, 100, fos);
  • Every time the system receives the SD card ready broadcast, it will go through all the files and folders of the SD card, and all the multimedia files that are traversed are saved in the Mediastore database with an index that contains the file name, path, size of the multimedia files.
  • Each time the gallery is opened, it does not traverse the SD card to get the picture, but rather the content provider obtains the picture from the Mediastore database and then reads the picture
  • When the system is powered on or when the SD card button is loaded, the system sends an SD card ready broadcast, and we can send the ready broadcast manually.

    Intent intent = new Intent();intent.setAction(Intent.ACTION_MEDIA_MOUNTED);intent.setData(Uri.fromFile(Environment.getExternalStorageDirectory()));sendBroadcast(intent);
5.2 Tearing clothes

Principle: Put on the underwear and wear the photos overlap display, underwear in the following, the user swipe the screen, the touch is the coat, the fingers pass through the pixels are set to transparent, underwear photos show out

    • Set a mobile listener on the screen to set the specified pixel to transparent

       iv.setOnTouchListener(new OnTouchListener() {    @Override    public boolean onTouch(View v, MotionEvent event) {        switch (event.getAction()) {        case MotionEvent.ACTION_MOVE:            int newX = (int) event.getX();            int newY = (int) event.getY();            // 把指定的像素变成透明            copyBm.setPixel(newX, newY, Color.TRANSPARENT);            iv.setImageBitmap(copyBm);            break;        }        return true;    }});
    • Setting one pixel at a time is too slow to touch the center of the pixel, with a radius of 5 to draw the circle, and the pixels in the circle to be all transparent

      for (int i = -5; i < 6; i++) {    for (int j = -5; j < 6; j++) {        if(Math.sqrt(i * i + j * j) <= 5)            copyBm.setPixel(newX + i, newY + j, Color.TRANSPARENT);    }}
5.3 Music player 5.3.1 Play Service
    • The code that plays the audio should run in the service and define a playback service Musicservice
    • Service definition play, stop, pause, Continueplay and other methods

      // 播放private void play() {    player.reset();    try {        player.setDataSource("sdcard/bzj.mp3");        player.prepare();    } catch (Exception e) {        e.printStackTrace();    }     player.start();}// 暂停private void pause() {    player.pause();}// 停止播放private void stop() {    player.stop();}// 继续播放private void continuePlay() {    player.start();}
    • To extract these methods into an interface Musicinterface
    • Define an intermediate human, inherit binder, implement Musicinterface
    • Start Musicservice First, then bind

      Intent intent = new Intent(this, MusicService.class);startService(intent);bindService(intent, conn, BIND_AUTO_CREATE);
5.3.2 Set progress bar based on playback progress
  • Gets the current playback time and the maximum time of the current audio

    int currentPosition = player.getCurrentPosition();int duration = player.getDuration();
  • Playback progress needs to be kept, constantly refresh the progress bar, using the timer every 500 milliseconds to get the playback progress
  • Send a message to handler, put the playback progress into the Message object, update the progress of the Seekbar in handler

    Timer timer = new Timer();timer.schedule(new TimerTask() {    @Override    public void run() {        int currentPosition = player.getCurrentPosition();        int duration = player.getDuration();        Message msg = Message.obtain();        // 把播放进度存入Message中        Bundle data = new Bundle();        data.putInt("currentPosition", currentPosition);        data.putInt("duration", duration);        msg.setData(data);        MainActivity.handler.sendMessage(msg);    }}, 5, 500);
  • Define handler in activity

    static Handler handler = new Handler(){    public void handleMessage(android.os.Message msg) {        // 取出消息携带的数据        Bundle data = msg.getData();        int currentPosition = data.getInt("currentPosition");        int duration = data.getInt("duration");        // 设置播放进度        sb.setMax(duration);        sb.setProgress(currentPosition);    };};
5.3.3 Drag the progress bar to change the playback progress
    • Set drag monitoring, drag to set the progress bar to the position where the drag is stopped

       // 给sb设置一个拖动侦听 sb.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {    //停止拖动时调用    @Override    public void onStopTrackingTouch(SeekBar seekBar) {        int progress = seekBar.getProgress();        mi.seekTo(progress);    }    // 开始拖动时调用              @Override    public void onStartTrackingTouch(SeekBar seekBar) {    }    // 拖动的时候不断调用                @Override    public void onProgressChanged(SeekBar seekBar, int progress,            boolean fromUser) {    
5.4 Video Player Surfaceview
  • High demand for real-time updates to the screen
  • Double buffering technology: There are two canvases in memory, a canvas is displayed to the screen, B canvas draws the next frame in memory, B is displayed to the screen after drawing, a continues to draw the next frame in memory
  • Play video is also used MediaPlayer, but unlike audio, to set the display in which Surfaceview

    SurfaceView sv = (SurfaceView) findViewById(R.id.sv);SurfaceHolder sh = sv.getHolder();MediaPlayer player = new MediaPlayer();player.reset();try {    player.setDataSource("sdcard/2.3gp");    player.setDisplay(sh);    player.prepare();} catch (Exception e) {    e.printStackTrace();}player.start();
  • Surfaceview is a heavyweight component that is created when it is visible
  • Set callback for Surfaceholder, similar to listening, to know the status of Surfaceview

    sh.addCallback(new Callback() {    // SurfaceView销毁时调用    @Override    public void surfaceDestroyed(SurfaceHolder holder) {    }    // SurfaceView创建时调用    @Override    public void surfaceCreated(SurfaceHolder holder) {    }    @Override    public void surfaceChanged(SurfaceHolder holder, int format, int width,            int height) {    }});
  • Once the Surfaceview is not visible, it will be destroyed and once visible, it will be created, stopped when destroyed, and played again when it is created again.
5.5 Camera
    • Start the system-provided camera program

      // 隐式启动系统提供的拍照ActivityIntent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);// 设置照片的保存路径File file = new File(Environment.getExternalStorageDirectory(), "haha.jpg"); intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file)); startActivityForResult(intent, 0);
    • Start the camera program provided by the system

      Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);File file = new File(Environment.getExternalStorageDirectory(), "haha.3gp"); intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file)); // 设置保存视频文件的质量intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);startActivityForResult(intent, 0);

Android Basics: DAY09 Multimedia programming

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.