ui.GalleryFileActivity.java Source code

Java tutorial

Introduction

Here is the source code for ui.GalleryFileActivity.java

Source

/*
 Copyright (c) 2012 Roman Truba
    
 Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
 documentation files (the "Software"), to deal in the Software without restriction, including without limitation
 the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
 permit persons to whom the Software is furnished to do so, subject to the following conditions:
    
 The above copyright notice and this permission notice shall be included in all copies or substantial
 portions of the Software.
    
 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
 TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
 THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH
 THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
package ui;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.gdpi.app.MyApp;
import com.gdpi.app.R;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import model.FileInfo;
import ru.truba.touchgallery.GalleryWidget.BasePagerAdapter.OnItemChangeListener;
import ru.truba.touchgallery.GalleryWidget.FilePagerAdapter;
import ru.truba.touchgallery.GalleryWidget.GalleryViewPager;
import utils.AlertUtils;
import utils.AudioRecordUtils;
import utils.Util;

/**
 * 
 * ???
 */

public class GalleryFileActivity extends Activity {

    private static final int START_RECORD = 10;//
    private static final int STOP_RECORD = 10 + 1;//?
    private static final int START_PLAY = 20;//
    protected static final int DELETE_VOICE_FILE = 10 + 2;
    private static final int MY_PERMISSION_RECORD_AUDIO = 100;//??

    private int RECORDER_TIME_MAXTIME = 60 * 5;
    private GalleryViewPager mViewPager;
    private List<String> items;
    private ArrayList<FileInfo> imageInfos;
    private int position = 0;
    private String name = "";
    private String direction;
    private String remark = "";
    private String voicePath = "";
    private MyApp app;
    private AudioRecordUtils recordUtils;// 
    private MediaPlayer mMediaPlayer = null;

    private Button recordBtn;
    private TextView voice_file;
    private TextView btm_file_name;
    private Button btm_remark_btn;
    private Button voice_del;
    private Button closeBtn;
    private LinearLayout voice_del_lly;

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case 1:
                voice_file.setText("");
                voice_del_lly.setVisibility(View.VISIBLE);
                recordBtn.setText("");
                break;
            case 2:
                if (updateThread != null)
                    mHandler.removeCallbacks(updateThread);
                recordBtn.setText("");
                break;
            case START_RECORD:
                startRecorder();
                break;
            case STOP_RECORD:
                stopRecorder();
                break;
            case START_PLAY:
                doPlay();
                break;
            case DELETE_VOICE_FILE:
                deleteVoiceFile();
                break;
            default:
                break;
            }
            super.handleMessage(msg);

        }

    };

    @SuppressWarnings("unchecked")
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.gallery_file_activity);
        try {
            app = (MyApp) getApplicationContext();
            items = new ArrayList<>();
            //??
            Bundle bundle = getIntent().getExtras();
            imageInfos = (ArrayList<FileInfo>) bundle.getSerializable("imageInfos");//
            position = bundle.getInt("position", 0);

            if (imageInfos != null) {
                for (FileInfo info : imageInfos) {
                    if (info.getType() != -1) {
                        items.add(info.getPath());
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        recordUtils = new AudioRecordUtils();

        voice_del_lly = (LinearLayout) findViewById(R.id.voice_del_lly);
        closeBtn = (Button) findViewById(R.id.header_close);
        recordBtn = (Button) findViewById(R.id.record_btn);
        voice_file = (TextView) findViewById(R.id.voice_file);
        btm_file_name = (TextView) findViewById(R.id.btm_file_name);
        btm_remark_btn = (Button) findViewById(R.id.btm_remark_btn);
        voice_del = (Button) findViewById(R.id.voice_del);

        closeBtn.setOnClickListener(onClickListener);
        recordBtn.setOnClickListener(onClickListener);
        voice_del.setOnClickListener(onClickListener);

        btm_remark_btn.setOnClickListener(onClickListener);
        btm_file_name.setOnClickListener(onClickListener);

        FilePagerAdapter pagerAdapter = new FilePagerAdapter(this, items);
        pagerAdapter.setOnItemChangeListener(new OnItemChangeListener() {
            @Override
            public void onItemChange(int currentPosition) {
                if (isRecording) {
                    stopRecorder();
                }
                position = currentPosition;
                voicePath = imageInfos.get(position).getVoicePath();
                setFileName();
                voice_del_lly.setVisibility(View.GONE);
                recordBtn.setText("");
                if (!TextUtils.isEmpty(voicePath) && new File(voicePath).exists()) {
                    mHandler.sendEmptyMessage(1);
                }
            }
        });
        mViewPager = (GalleryViewPager) findViewById(R.id.viewer);
        mViewPager.setOffscreenPageLimit(3);
        mViewPager.setAdapter(pagerAdapter);
        mViewPager.setCurrentItem(position);
    }

    private OnClickListener onClickListener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
            case R.id.header_close://?
                release();
                addImage();
                finish();
                break;
            case R.id.record_btn://
                if (ContextCompat.checkSelfPermission(GalleryFileActivity.this,
                        Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED) {
                    try {
                        if (!isRecording) {
                            if (voice_del_lly.getVisibility() == View.VISIBLE) {
                                mHandler.sendEmptyMessage(START_PLAY);
                            } else {
                                mHandler.sendEmptyMessage(START_RECORD);
                            }
                        } else {
                            mHandler.sendEmptyMessage(STOP_RECORD);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    // ??????)
                    ActivityCompat.requestPermissions(GalleryFileActivity.this,
                            new String[] { Manifest.permission.RECORD_AUDIO }, MY_PERMISSION_RECORD_AUDIO);
                }

                break;
            case R.id.voice_del:
                mHandler.sendEmptyMessage(DELETE_VOICE_FILE);
                break;
            case R.id.btm_file_name:
            case R.id.btm_remark_btn:
                AlertUtils.showEdit(GalleryFileActivity.this, imageInfos.get(position).getRemarks(),
                        new AlertUtils.OnEditListener() {

                            @Override
                            public void onTextChanged(String str) {
                                remark = str;
                            }

                            @Override
                            public void onEditFinish(String str) {
                                if (!TextUtils.isEmpty(str)) {
                                    imageInfos.get(position).setRemarks(str);
                                    setFileName();
                                }
                            }
                        });
                break;
            default:
                break;
            }
        }
    };
    private String savePath;
    private String fileName;
    private boolean isRecording = false;
    private long startVoiceT = 0;// 
    private long endVoiceT = 0;// ?
    private int voiceLen = 0;

    // 
    private void startRecorder() {
        savePath = getRecorderPath();
        // SD??
        if (TextUtils.isEmpty(savePath)) {
            Toast.makeText(this, "SD??", Toast.LENGTH_SHORT).show();
            return;
        }
        fileName = System.currentTimeMillis() + ".mp3";// ??

        isRecording = true;
        voiceLen = 0;
        startVoiceT = System.currentTimeMillis();

        recordBtn.setText("?");
        voice_del_lly.setVisibility(View.VISIBLE);
        voice_file.setText(Util.formatLongToTimeStr(voiceLen));
        try {
            recordUtils.start(savePath, fileName);
        } catch (Exception e) {
            e.printStackTrace();
        }
        mHandler.postDelayed(mTimerTask, 1000);
    }

    // ??
    private void stopRecorder() {
        endVoiceT = System.currentTimeMillis();
        long voiceT = endVoiceT - startVoiceT;
        isRecording = false;
        mHandler.removeCallbacks(mTimerTask);
        recordUtils.stop();

        voiceLen = (int) (voiceT / 1000);

        voicePath = savePath + fileName;
        if (!TextUtils.isEmpty(voicePath) && new File(voicePath).exists()) {
            imageInfos.get(position).setVoicePath(voicePath);
            voice_del_lly.setVisibility(View.VISIBLE);
            voice_file.setText(Util.formatLongToTimeStr(voiceLen));
        }
        recordBtn.setText("");
    }

    // 
    private void deleteVoiceFile() {
        release();
        voice_file.setText("00:00");
        voice_del_lly.setVisibility(View.GONE);
        try {
            File newPath = new File(voicePath);
            if (newPath.exists()) {
                newPath.delete();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        imageInfos.get(position).setVoicePath(null);
        recordBtn.setText("");
    }

    /***
     * ?
     */
    private void release() {
        if (isRecording) {
            stopRecorder();
        }
        if (mMediaPlayer != null) {
            if (mMediaPlayer.isPlaying()) {
                mMediaPlayer.stop();
                mMediaPlayer.reset();
            }
            if (updateThread != null)
                mHandler.removeCallbacks(updateThread);
            mMediaPlayer.release();
            mMediaPlayer = null;
        }
    }

    Runnable updateThread = new Runnable() {
        public void run() {
            //???
            if (mMediaPlayer != null) {
                int time = mMediaPlayer.getCurrentPosition() / 1000;
                voice_file.setText(Util.formatLongToTimeStr(time));
            }
            //?100??
            mHandler.postDelayed(updateThread, 100);
        }
    };

    // 
    private void doPlay() {
        recordBtn.setText("?");
        if (!TextUtils.isEmpty(voicePath)) {
            try {
                if (mMediaPlayer != null && mMediaPlayer.isPlaying()) {
                    mMediaPlayer.stop();
                    mMediaPlayer.reset();
                    mHandler.sendEmptyMessage(2);
                    return;
                }
                if (mMediaPlayer == null) {
                    mMediaPlayer = new MediaPlayer();
                }
                mMediaPlayer.reset();
                mMediaPlayer.setDataSource(voicePath);
                mMediaPlayer.prepare();

            } catch (Exception e) {
                e.printStackTrace();
            }
            mMediaPlayer.start();
            mMediaPlayer.setOnPreparedListener(new OnPreparedListener() {

                @Override
                public void onPrepared(MediaPlayer mp) {
                    int time = mp.getDuration() / 1000;
                    voice_file.setText(Util.formatLongToTimeStr(time));
                    mHandler.post(updateThread);
                }
            });
            mMediaPlayer.setOnCompletionListener(new OnCompletionListener() {

                @Override
                public void onCompletion(MediaPlayer mp) {
                    mp.stop();
                    mp.reset();
                    mHandler.sendEmptyMessage(2);

                }
            });

            mMediaPlayer.setOnErrorListener(new OnErrorListener() {

                @Override
                public boolean onError(MediaPlayer mp, int arg1, int arg2) {
                    mp.stop();
                    mp.reset();
                    mHandler.sendEmptyMessage(2);
                    return false;
                }
            });
        }

    }

    //
    private Runnable mTimerTask = new Runnable() {
        //      int i = 0;
        @Override
        public void run() {
            if (!isRecording)
                return;
            voiceLen++;
            if (voiceLen == RECORDER_TIME_MAXTIME) {
                Toast.makeText(GalleryFileActivity.this, "", Toast.LENGTH_SHORT).show();
                return;
            }
            voice_file.setText(Util.formatLongToTimeStr(voiceLen));
            mHandler.postDelayed(mTimerTask, 1000);
        }

    };

    private String getRecorderPath() {
        String savePath = "";
        try {
            // ?SD?
            String storageState = Environment.getExternalStorageState();
            if (storageState.equals(Environment.MEDIA_MOUNTED)) {
                savePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/GPDI/";// 

                File savedir = new File(savePath);
                if (!savedir.exists()) {
                    savedir.mkdirs();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return savePath;
    }

    @Override
    protected void onPause() {
        if (mMediaPlayer != null) {
            if (mMediaPlayer.isPlaying()) {
                mMediaPlayer.pause();
            }
        }
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        release();
        super.onDestroy();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            addImage();
        }
        return super.onKeyDown(keyCode, event);
    }

    public void addImage() {
        if (imageInfos != null && imageInfos.size() > 0) {
            app.getChooseImages().clear();
            app.getChooseImages().addAll(imageInfos);
        }
    }

    public void setFileName() {
        name = TextUtils.isEmpty(imageInfos.get(position).getName()) ? "" : imageInfos.get(position).getName();
        remark = TextUtils.isEmpty(imageInfos.get(position).getRemarks()) ? ""
                : imageInfos.get(position).getRemarks();
        direction = (TextUtils.isEmpty(imageInfos.get(position).getDirection()) ? ""
                : "_" + imageInfos.get(position).getDirection());
        btm_file_name
                .setText(String.valueOf("??" + name + "_" + (position + 1) + direction + "_" + remark));
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
            @NonNull int[] grantResults) {

        switch (requestCode) {
        case MY_PERMISSION_RECORD_AUDIO:
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // ?????SDK????????
                try {
                    if (!isRecording) {
                        if (voice_del_lly.getVisibility() == View.VISIBLE) {
                            mHandler.sendEmptyMessage(START_PLAY);
                        } else {
                            mHandler.sendEmptyMessage(START_RECORD);
                        }
                    } else {
                        mHandler.sendEmptyMessage(STOP_RECORD);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                // ?????
                Toast.makeText(GalleryFileActivity.this,
                        "???????", Toast.LENGTH_SHORT)
                        .show();
            }
            break;
        default:
            break;
        }
    }
}