Java tutorial
/* * Copyright (c) 2016 <kaku201313@163.com | 3772304@qq.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.kaku.weac.fragment; import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.os.Message; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.AdapterView.OnItemLongClickListener; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import com.kaku.weac.R; import com.kaku.weac.activities.RecordDeleteActivity; import com.kaku.weac.activities.RecordDeleteBatchActivity; import com.kaku.weac.activities.RecordDetailActivity; import com.kaku.weac.activities.RecordOperateActivity; import com.kaku.weac.activities.RecordRenameActivity; import com.kaku.weac.adapter.RingSelectAdapter; import com.kaku.weac.bean.RingSelectItem; import com.kaku.weac.common.WeacConstants; import com.kaku.weac.util.AudioPlayer; import com.kaku.weac.util.AudioRecorder; import com.kaku.weac.util.LogUtil; import com.kaku.weac.util.MyUtil; import com.kaku.weac.util.RingItemComparator; import com.kaku.weac.util.ToastUtil; import java.io.File; import java.lang.ref.WeakReference; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; /** * Fragment * * @author * @version 1.0 2015/05 */ public class RecorderFragment extends BaseFragment implements OnClickListener { /** * Log tag RecorderFragment */ private static final String LOG_TAG = "RecorderFragment"; /** * ?requestCode */ private static final int REQUEST_RECORD_OPERATE = 1; /** * ???requestCode */ private static final int REQUEST_RENAME = 2; /** * requestCode */ private static final int REQUEST_DELETE = 3; /** * ??List */ private List<Map<String, String>> mList; /** * ??Adapter */ RingSelectAdapter mRecorderAdapter; /** * */ private ImageButton mRecordBtn; /** * ? */ private ImageButton mStopBtn; /** * ??? */ private TextView mRecordButtonInfo; /** * ??? */ private String mRingName; /** * ? */ private ViewGroup mRecordMic; /** * ? */ private ImageView mRecordMicStatusImage; /** * */ private TextView mRecordTime; /** * ? */ private boolean mIsRecording = false; /** * ? */ private int mPosition = 0; /** * */ private static final int UPDATE_TIME = 1; /** * ?Handler */ private MicStatusHandler mMicStatusHandler; /** * Handler */ private RecordTimeHandler mRecordTimeHandler; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mList = new ArrayList<>(); // ?????? if (RingSelectFragment.sRingName != null) { mRingName = RingSelectFragment.sRingName; } else { // ?????? SharedPreferences share = getActivity().getSharedPreferences(WeacConstants.EXTRA_WEAC_SHARE, Activity.MODE_PRIVATE); mRingName = share.getString(WeacConstants.RING_NAME, ""); } // List setRingList(); mRecorderAdapter = new RingSelectAdapter(getActivity(), mList, mRingName); mMicStatusHandler = new MicStatusHandler(this); mRecordTimeHandler = new RecordTimeHandler(this); } @Override public void onStart() { LogUtil.i(LOG_TAG, "onStart()"); super.onStart(); } @Override public void onResume() { LogUtil.i(LOG_TAG, "onResume()"); super.onResume(); // ?? refreshList(); } @Override public void onPause() { LogUtil.i(LOG_TAG, "onPause()"); // ? recordStop(); super.onPause(); } @Override public void onStop() { LogUtil.i(LOG_TAG, "onStop()"); super.onStop(); } @Override public void onDestroy() { LogUtil.i(LOG_TAG, "onDestroy()"); super.onDestroy(); if (mMicStatusHandler != null) { mMicStatusHandler.removeCallbacksAndMessages(null); } if (mRecordTimeHandler != null) { mRecordTimeHandler.removeCallbacksAndMessages(null); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { LogUtil.i(LOG_TAG, "onCreateView()"); View view = inflater.inflate(R.layout.fm_ring_recorder, container, false); // ListView ListView recordListView = (ListView) view.findViewById(R.id.ring_record_lv); // ListTextView TextView emptyView = (TextView) view.findViewById(R.id.ring_record_empty); // List recordListView.setEmptyView(emptyView); recordListView.setAdapter(mRecorderAdapter); // ?? recordListView.setSelection(mPosition); recordListView.setOnItemClickListener(new OnItemClickListenerImpl()); recordListView.setOnItemLongClickListener(new onItemLongClickListenerImpl()); // mRecordBtn = (ImageButton) view.findViewById(R.id.ring_record_record); mStopBtn = (ImageButton) view.findViewById(R.id.ring_record_stop); mRecordButtonInfo = (TextView) view.findViewById(R.id.ring_record_button_info); mRecordBtn.setOnClickListener(this); mStopBtn.setOnClickListener(this); // ? mRecordMic = (ViewGroup) view.findViewById(R.id.ring_record_mic_llyt); mRecordMicStatusImage = (ImageView) view.findViewById(R.id.ring_record_mic_status); mRecordTime = (TextView) view.findViewById(R.id.ring_record_time); return view; } private class OnItemClickListenerImpl implements OnItemClickListener { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Map<String, String> map = mRecorderAdapter.getItem(position); // ??? String ringName = map.get(WeacConstants.RING_NAME); // ?? String ringUrl = map.get(WeacConstants.RING_URL); // ?? mRecorderAdapter.updateSelection(ringName); // ? mRecorderAdapter.notifyDataSetChanged(); // AudioPlayer.getInstance(getActivity()).play(ringUrl, false, false); // ???? RingSelectItem.getInstance().setRingPager(2); ViewPager pager = (ViewPager) getActivity().findViewById(R.id.fragment_ring_select_sort); PagerAdapter f = pager.getAdapter(); LocalMusicFragment localMusicFragment = (LocalMusicFragment) f.instantiateItem(pager, 1); SystemRingFragment systemRingFragment = (SystemRingFragment) f.instantiateItem(pager, 0); // ?? if (localMusicFragment.mLocalMusicAdapter != null) { localMusicFragment.mLocalMusicAdapter.updateSelection(""); localMusicFragment.mLocalMusicAdapter.notifyDataSetChanged(); } // ? if (systemRingFragment.mSystemRingAdapter != null) { systemRingFragment.mSystemRingAdapter.updateSelection(""); systemRingFragment.mSystemRingAdapter.notifyDataSetChanged(); } } } private class onItemLongClickListenerImpl implements OnItemLongClickListener { @Override public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { Intent intent = new Intent(getActivity(), RecordOperateActivity.class); intent.putExtra(WeacConstants.POSITION, position); startActivityForResult(intent, REQUEST_RECORD_OPERATE); return true; } } @Override public void onClick(View v) { switch (v.getId()) { // case R.id.ring_record_record: // XXX? // if (!MyUtil.isHasSDCard()) { ToastUtil.showShortToast(getActivity(), getString(R.string.no_sd_card)); return; } // String fileName = getRecordDirectory(); File file = new File(fileName); if (!file.exists()) { if (!file.mkdirs()) { return; } } // ? String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()).format(new Date()); // ?? fileName += String.format(getActivity().getResources().getString(R.string.record_file_name), time); // ?? AudioPlayer.getInstance(getActivity()).playRaw(R.raw.record_start, false, false); // 200?? try { Thread.sleep(200); } catch (InterruptedException e) { e.printStackTrace(); } // AudioRecorder.getInstance(getActivity()).record(fileName); // if (!AudioRecorder.getInstance(getActivity()).mIsStarted) { // File f = new File(fileName); boolean result = false; if (f.exists()) { result = f.delete(); } if (!result) { LogUtil.d(LOG_TAG, getString(R.string.error_delete_fail)); } break; } // ?? mRecordBtn.setVisibility(View.GONE); // ? mStopBtn.setVisibility(View.VISIBLE); // ??? mRecordButtonInfo.setText(getString(R.string.click_stop)); // ? mRecordMic.setVisibility(View.VISIBLE); // ??? mIsRecording = true; // ???? new Thread(new UpdateMicStatus()).start(); mRecordTime.setText(getResources().getString(R.string.zero_zero)); new Thread(new updateRecorderTime()).start(); // Handler handler = new Handler(); // Runnable stopRecordRun = new Runnable() { // @Override // public void run() { // // ? // recordStop(); // ToastUtil.showLongToast(getActivity(), "10"); // } // // }; // // 10?? // handler.postDelayed(stopRecordRun, // WeacConstants.MAX_RECORD_LENGTH); break; case R.id.ring_record_stop: // ? recordStop(); break; } } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode != Activity.RESULT_OK) { return; } switch (requestCode) { // ? case REQUEST_RECORD_OPERATE: int position = data.getIntExtra(WeacConstants.POSITION, 0); Map<String, String> map = mRecorderAdapter.getItem(position); // ?? String ringName = map.get(WeacConstants.RING_NAME); // String ringUrl = map.get(WeacConstants.RING_URL); // ? int type = data.getIntExtra(WeacConstants.TYPE, -1); switch (type) { // ??? case 1: Intent intent1 = new Intent(getActivity(), RecordRenameActivity.class); intent1.putExtra(WeacConstants.RING_NAME, ringName); intent1.putExtra(WeacConstants.RING_URL, ringUrl); startActivityForResult(intent1, REQUEST_RENAME); break; // case 2: Intent intent2 = new Intent(getActivity(), RecordDeleteActivity.class); intent2.putExtra(WeacConstants.RING_URL, ringUrl); startActivityForResult(intent2, REQUEST_DELETE); break; // ? case 3: Intent intent3 = new Intent(getActivity(), RecordDeleteBatchActivity.class); intent3.putExtra(WeacConstants.RING_NAME, ringName); intent3.putExtra(WeacConstants.RING_URL, ringUrl); startActivity(intent3); break; // case 4: Intent intent4 = new Intent(getActivity(), RecordDetailActivity.class); intent4.putExtra(WeacConstants.RING_NAME, ringName); intent4.putExtra(WeacConstants.RING_URL, ringUrl); startActivity(intent4); break; default: break; } break; // ??? case REQUEST_RENAME: String oldUrl = data.getStringExtra(WeacConstants.RING_URL); String newUrl = data.getStringExtra(WeacConstants.NEW_URL); File oldFile = new File(oldUrl); // ??? boolean result = oldFile.renameTo(new File(newUrl)); if (result) { ToastUtil.showShortToast(getActivity(), getString(R.string.rename_success)); } // refreshList(); break; case REQUEST_DELETE: String ringUrl2 = data.getStringExtra(WeacConstants.RING_URL); File file = new File(ringUrl2); // boolean result2 = file.delete(); if (result2) { ToastUtil.showShortToast(getActivity(), getString(R.string.delete_success)); } // refreshList(); break; } } /** * List */ private void setRingList() { if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { return; } // String fileName = getRecordDirectory(); File file = new File(fileName); // ? if (!file.exists()) { return; } // File[] files = file.listFiles(); for (File file1 : files) { // ?? String ringName = file1.getName(); // String prefix=fileName.substring(fileName.lastIndexOf(".")+1); if (ringName.endsWith(".amr")) { // ?? ringName = MyUtil.removeEx(ringName); // ?? String ringUrl = file1.getAbsolutePath(); Map<String, String> map = new HashMap<>(); map.put(WeacConstants.RING_NAME, ringName); map.put(WeacConstants.RING_URL, ringUrl); mList.add(map); } } // ? Collections.sort(mList, new RingItemComparator()); // ???? for (int i = 0; i < mList.size(); i++) { Map<String, String> map = mList.get(i); String ringName = map.get(WeacConstants.RING_NAME); if (ringName.equals(mRingName)) { mPosition = i; RingSelectItem.getInstance().setRingPager(2); } } } /** * */ private void refreshList() { mList.clear(); setRingList(); mRecorderAdapter.notifyDataSetChanged(); } /** * ? */ private void recordStop() { // if (mIsRecording) { // ? AudioRecorder.getInstance(getActivity()).stop(); // ??? AudioPlayer.getInstance(getActivity()).playRaw(R.raw.record_stop, false, false); // ??? mStopBtn.setVisibility(View.GONE); // mRecordBtn.setVisibility(View.VISIBLE); // ??? mRecordButtonInfo.setText(getString(R.string.click_record)); // refreshList(); // ??? mRecordMic.setVisibility(View.GONE); // ???? mIsRecording = false; // ?? mRecordBtn.setClickable(false); new Thread(new Runnable() { @Override public void run() { try { Thread.sleep(500); mRecordBtn.setClickable(true); } catch (Exception e) { LogUtil.e(LOG_TAG, "run" + e.toString()); } } }).start(); } } /** * ? * * @return */ private String getRecordDirectory() { // String fileName = Environment.getExternalStorageDirectory().getAbsolutePath(); // fileName += WeacConstants.RECORD_SAVE_PATH; return fileName; } /** * ? */ private class UpdateMicStatus implements Runnable { /** * ? */ private static final int BASE = 3; /** * ?? */ private static final int SPACE = 100; /** * ? */ private int micStatus; /** * ? */ private int db; @Override public void run() { while (mIsRecording) { try { if (AudioRecorder.getInstance(getActivity()).mRecorder == null) { return; } // ? double ratio = (double) AudioRecorder.getInstance(getActivity()).mRecorder.getMaxAmplitude() / BASE; if (ratio > 1) { // ??dB=20lg(A/B) db = (int) (20 * Math.log10(ratio)); } else { db = 0; } Thread.sleep(SPACE); // LogUtil.d(LOG_TAG, "?" + db); if (db < 27) { micStatus = 1; } else if (db < 32) { micStatus = 2; } else if (db < 38) { micStatus = 3; } else if (db < 45) { micStatus = 4; } else if (db < 55) { micStatus = 5; } else if (db < 65) { micStatus = 6; } else if (db < 75) { micStatus = 7; } else if (db < 80) { micStatus = 8; } else { micStatus = 9; } Message msg = mMicStatusHandler.obtainMessage(micStatus); mMicStatusHandler.sendMessage(msg); } catch (Exception e) { LogUtil.e(LOG_TAG, "run" + e.toString()); } } } } /** * */ private class updateRecorderTime implements Runnable { // private int time = 1; @Override public void run() { while (mIsRecording) { try { Thread.sleep(1000); CharSequence recordTime = new SimpleDateFormat("mm:ss", Locale.getDefault()) .format(time * 1000); Message msg = mRecordTimeHandler.obtainMessage(UPDATE_TIME, recordTime); mRecordTimeHandler.sendMessage(msg); time++; } catch (Exception e) { LogUtil.e(LOG_TAG, "run" + e.toString()); } } } } /** * ?Handler */ static class MicStatusHandler extends Handler { WeakReference<RecorderFragment> mWeakReference; public MicStatusHandler(RecorderFragment recorderFragment) { mWeakReference = new WeakReference<>(recorderFragment); } @Override public void handleMessage(Message msg) { super.handleMessage(msg); RecorderFragment recorderFragment = mWeakReference.get(); // ? switch (msg.what) { case 1: recorderFragment.mRecordMicStatusImage.setImageResource(R.drawable.ic_ring_record_mic_status1); break; case 2: recorderFragment.mRecordMicStatusImage.setImageResource(R.drawable.ic_ring_record_mic_status2); break; case 3: recorderFragment.mRecordMicStatusImage.setImageResource(R.drawable.ic_ring_record_mic_status3); break; case 4: recorderFragment.mRecordMicStatusImage.setImageResource(R.drawable.ic_ring_record_mic_status4); break; case 5: recorderFragment.mRecordMicStatusImage.setImageResource(R.drawable.ic_ring_record_mic_status5); break; case 6: recorderFragment.mRecordMicStatusImage.setImageResource(R.drawable.ic_ring_record_mic_status6); break; case 7: recorderFragment.mRecordMicStatusImage.setImageResource(R.drawable.ic_ring_record_mic_status7); break; case 8: recorderFragment.mRecordMicStatusImage.setImageResource(R.drawable.ic_ring_record_mic_status8); break; case 9: recorderFragment.mRecordMicStatusImage.setImageResource(R.drawable.ic_ring_record_mic_status9); break; } } } /** * Handler */ static class RecordTimeHandler extends Handler { WeakReference<RecorderFragment> mWeakReference; public RecordTimeHandler(RecorderFragment recorderFragment) { mWeakReference = new WeakReference<>(recorderFragment); } @Override public void handleMessage(Message msg) { super.handleMessage(msg); RecorderFragment recorderFragment = mWeakReference.get(); switch (msg.what) { case UPDATE_TIME: recorderFragment.mRecordTime.setText(msg.obj.toString()); break; } } } }