thinkwee
3/12/2017 - 8:05 AM

大创Android代码片段

public void AppStartCounts(Context context){
        /**
         * Created by Thinkwee on 2016/10/13 0013 11:12
         * Parameter [context]上下文
         * Return void
         * CLASS:MainActivity
         * FILE:MainActivity.java
         * TODO:统计软件启动次数 startcounts传到个人统计页面
         */
        try {
            File file=new File(context.getCacheDir(),"StartCounts.txt");
            if (file.exists()){
                FileInputStream fis=new FileInputStream(file);
                BufferedReader br=new BufferedReader(new InputStreamReader(fis));
                String temp=br.readLine();
                if (temp==null){
                    startcounts=1;
                    Log.i(TAG,"Startcounts文件读错误");
                }
                else{
                    startcounts=Integer.parseInt(temp);
                    Log.i(TAG,"第"+temp+"次启动软件");
                }
                fis.close();
                br.close();
                FileOutputStream fos=new FileOutputStream(file);
                startcounts++;
                fos.write(Integer.toString(startcounts).getBytes());
                fos.close();
            }else{
                file.createNewFile();
                FileOutputStream fos=new FileOutputStream(file);
                Log.i(TAG,"首次创建Startcounts");
                fos.write(Integer.toString(startcounts).getBytes());
                fos.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
 public void DownloadHtml(Context context){
        /**
         * Created by Thinkwee on 2016/10/13 0013 11:12
         * Parameter [context]上下文
         * Return void
         * CLASS:MainActivity
         * FILE:MainActivity.java
         * TODO:离线下载html
         */
        try {
            File file=new File(context.getCacheDir(),"DownloadHtml.txt");
            if (!file.exists()){
                file.delete();
            }
            file.createNewFile();
            FileOutputStream fos=new FileOutputStream(file,false);
            final TimeInfo timeinfo= new TimeInfo();
            timeinfo.timesetting();
            fos.write((timeinfo.Timestring+"\n").getBytes());
            fos.write((htmlbody).getBytes());
            Log.i(TAG,"已离线htmlbody"+ htmlbody);
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
// MediaPlayer播放Midi

public class PlayFragment extends Fragment {
    private View v;
    private Button bt_play,bt_stop;
    private TextView tv_choosetoplay;
    private MediaPlayer player;
    private String TAG="MIDI";


    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        v = inflater.inflate(R.layout.fragment_play, container, false);
        return v;
    }

    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        bt_play = (Button) getActivity().findViewById(R.id.bt_play);
        bt_stop = (Button) getActivity().findViewById(R.id.bt_stop);
        tv_choosetoplay = (TextView) getActivity().findViewById(R.id.tv_choosetoplay);

        bt_play.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (player != null){
                    player.pause();
                }
                player=MediaPlayer.create(getActivity(),R.raw.test1);
                player.start();
            }
        });

        bt_stop.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v){
                if (player != null)
                {
                    player.stop();
                }
            }
        });
    }
// 用AudioTrack类重放录制的pcm文件

private class PlayTask extends AsyncTask<Void, Integer, Void> {
        @Override
        protected Void doInBackground(Void... arg0) {
            isPlaying = true;
            int bufferSize = AudioTrack.getMinBufferSize(frequence, channelConfig, audioEncoding);
            short[] buffer = new short[bufferSize / 4];
            try {
                //定义输入流,将音频写入到AudioTrack类中,实现播放
                DataInputStream dis = new DataInputStream(new BufferedInputStream(new FileInputStream(audioFile)));
                //实例AudioTrack
                AudioTrack track = new AudioTrack(AudioManager.STREAM_MUSIC, frequence, channelConfig, audioEncoding, bufferSize, AudioTrack.MODE_STREAM);
                //开始播放
                track.play();
                //由于AudioTrack播放的是流,所以,我们需要一边播放一边读取
                while (isPlaying && dis.available() > 0) {
                    int i = 0;
                    while (dis.available() > 0 && i < buffer.length) {
                        buffer[i] = dis.readShort();
                        i++;
                    }
                    //然后将数据写入到AudioTrack中
                    track.write(buffer, 0, buffer.length);

                }

                //播放结束
                track.stop();
                dis.close();
            } catch (Exception e) {
                // TODO: handle exception
            }
            return null;
        }
    }
// 录制wav
// 以pcm编码保存

private class RecordTask extends AsyncTask<Void, Integer, Void> {
        @Override
        protected Void doInBackground(Void... arg0) {
            isRecording = true;
            try {
                //开通输出流到指定的文件
                DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(audioFile)));
                //根据定义好的几个配置,来获取合适的缓冲大小
                int bufferSize = AudioRecord.getMinBufferSize(frequence, channelConfig, audioEncoding);
                //实例化AudioRecord
                AudioRecord record = new AudioRecord(MediaRecorder.AudioSource.MIC, frequence, channelConfig, audioEncoding, bufferSize);
                //定义缓冲
                short[] buffer = new short[bufferSize];

                //开始录制
                record.startRecording();

                int r = 0; //存储录制进度
                //定义循环,根据isRecording的值来判断是否继续录制
                while (isRecording) {
                    //从bufferSize中读取字节,返回读取的short个数
                    //这里老是出现buffer overflow,不知道是什么原因,试了好几个值,都没用,TODO:待解决
                    int bufferReadResult = record.read(buffer, 0, buffer.length);
                    //循环将buffer中的音频数据写入到OutputStream中
                    for (int i = 0; i < bufferReadResult; i++) {
                        dos.writeShort(buffer[i]);
                    }
                    publishProgress(new Integer(r)); //向UI线程报告当前进度
                    r++; //自增进度值
                }
                //录制结束
                record.stop();
                Log.v("The DOS available:", "::" + audioFile.length());
                dos.close();
            } catch (Exception e) {
                // TODO: handle exception
            }
            return null;
        }
    }
// 读取之前录制的文件到FileInputStream中
// 从FileinputStream中读到缓存,再将缓存写入绑定了socket的OutputStream的DataOutputStream,上传到服务器
soc_send.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v){
                DataOutputStream out=null;
                FileInputStream reader=null;
                int buffersize=20480;
                int read=0;
                byte[] buf = new byte[buffersize];
                try {
                    File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/data/files/recording.pcm");
                    reader = new FileInputStream(file);
                    out = new DataOutputStream(socket.getOutputStream());
                    while((read=reader.read(buf,0,buf.length))!=-1){
                        out.write(buf,0,read);
                    }
                    Log.i(TAG2,"发送文件完成");
                    out.flush();
                    socket.shutdownOutput();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
// 新建socket在地址IPget,端口port
// msg传到handler更新用户界面提示成功连接

private class StartThread extends  Thread{
        @Override
        public void run(){
            try{
                socket= new Socket(IPget,port);
                if(socket.isConnected()){//成功连接获取socket对象则发送成功消息
                    Log.i(TAG,"isConnected");
                    Message msg0 = myhandler.obtainMessage();
                    msg0.what=0;
                    myhandler.sendMessage(msg0);
                }
            } catch (IOException e) {
                Log.i(TAG,"Connect Failed");
                e.printStackTrace();
            }
        }
    }
               bmp = BitmapFactory.decodeStream(bis);
               ByteArrayOutputStream OutPut = new ByteArrayOutputStream();
               bmp.compress(Bitmap.CompressFormat.PNG, 100,OutPut);
               msg.what = 5;
               myhandler.sendMessage(msg);
try {
                    StringBuilder strbuild = new StringBuilder();
                    int bisLength=bis.available();
                    byte[] byteArray=new byte[SIZE];
                    int tmp=0;
                    while((tmp=bis.read(byteArray))!=-1){
                        strbuild.append(new String(byteArray,0,tmp));
                        System.out.println("每次读取字节数量:"+tmp);
                        System.out.println("文件中剩余字节数:"+is.available());
                    }

                    System.out.println(String.format("缓冲区读取流返回的大小:%d",bisLength));
                    System.out.println("文件的内容:"+strbuild.toString());
                    System.out.println("字符串长度:"+strbuild.toString().length());
                    char[] cTmp=strbuild.toString().toCharArray();
                    System.out.println("字符串->字符数组长度:"+cTmp.length);
                    Message msg = myhandler.obtainMessage();
                    msg.what = 1;
                    msg.obj = strbuild.toString();
                    myhandler.sendMessage(msg);
                } catch (IOException e) {
                    e.printStackTrace();
                }