2018年8月23日 星期四

?attr/actionBarSize报错


升级android studio3.0.1之后 项目布局中的

?attr/actionBarSize全部标红报错,更改成

android:layout_height="?android:attr/actionBarSize" 

2018年8月14日 星期二

建立文件夾,文件寫入,內存,SD卡剩餘空間

        // ---先檢查權限-6.0 --------------------------
        int permissionCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},REQUEST_READ_PHONE_STATE);
        }


//檢查SD
    public static boolean isSDCardEnable(){
        return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState());
    }

            //获取内存可用剩余空间
            long romFreeSpace=Environment.getDataDirectory().getFreeSpace();
            //获取SD卡可用剩余空间
            long SDFreeSpace= Environment.getExternalStorageDirectory().getFreeSpace();
            String formatter= android.text.format.Formatter.formatFileSize(this,romFreeSpace);
            String SDformatter= android.text.format.Formatter.formatFileSize(this,SDFreeSpace);
            Log.e("Debug","內存可用"+ formatter);
            Log.e("Debug","sd卡可用"+ SDformatter);



 String directoryPath= Environment.getExternalStorageDirectory().getAbsolutePath()+File.separator+"File_Text_Demo"+File.separator;  // 路徑  路徑資料夾下
 String FileName= directoryPath+getNowTime()+".txt";  // 路徑 + 檔案名稱
    //建立文件夾 及 檔案
    public void CreatText(){
        File file=new File(directoryPath);
        if(!file.exists()){
            try {
               //按照指定的路径创建文件夹
                file.mkdirs();
            }catch (Exception e){

            }
        }
         File dir= new File(FileName);
        if(!dir.exists()){
            try{
                dir.createNewFile(); //在指定的文件中創建文件
                Log.e("Debug"," 創建成功");

            }catch (Exception e){
            }
        }
    }

//文件內容
 public void print( String str){
        FileWriter fw=null;
        BufferedWriter bw=null;
        String datetime="";
        try{
            CreatText();
            SimpleDateFormat tempDate=new SimpleDateFormat("yyyy-MM-dd  hh:mm:ss");
            datetime= tempDate.format(new Date().toString());   //轉為字串
            fw= new FileWriter(FileName,true);
            // 创建FileWriter对象,用来写入字符流
       /**
                     * 如果想要每次写入,清除之前的内容,使用FileOutputStream流
                     */
          bw=new BufferedWriter(fw);// 将缓冲对文件的输出
          String myreadline= datetime+","+str;
          bw.write(myreadline + "\n"); //寫入文件
            bw.newLine();
            bw.flush();
            bw.close();
            fw.close();
        } catch (IOException e) {
            e.printStackTrace();
            try {
                bw.close();
                fw.close();
            } catch (IOException e1) {
            }
        }
    }


//當前時間
    public static String getNowTime(){
        //  SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date(System.currentTimeMillis());
        return simpleDateFormat.format(date);
    }

文件路径用的File.separator和直接打“\\”有什么区别

在windows中的文件分隔符是 \ 和 /都可以

但是在Linux中,文件分隔符只能是/

所以用了\\的程序在Linux下会出问题。

而File.separator是系统默认的文件分割符号,屏蔽了这些系统的区别。

用File.separator保证了在任何系统下不会出错。

2018年8月13日 星期一

OkHttpClient get 數據

private void getOkhttp(){
runOnUiThread(new Runnable() {
            @Override
            public void run() {

                OkHttpClient client=new OkHttpClient.Builder()
                        .connectTimeout(10, TimeUnit.SECONDS)
                        .readTimeout(10,TimeUnit.SECONDS)
                        .build();

  String url="https://www.google.com.tw/";
                Request request = new Request.Builder()
                        .get()
                        .url(url)
                        .build();
           
                client.newCall(request).enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        Log.e("Debug"," get----------onFailure--->");
                    }
                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                       final String string = response.body().string();
                    //    byte[] b = response.body().bytes(); //获取数据的bytes
                   //  String info = new String(b, "gb2312"); //然后将其转为gb2312
                   
                    }
                });

            }
        });
}


    public void get2(){

            OkHttpClient client=new OkHttpClient.Builder()
                        .connectTimeout(10, TimeUnit.SECONDS)
                        .readTimeout(10,TimeUnit.SECONDS)
                        .build();


        //post
        String a="050";
        String b="050"; 

        RequestBody requestBodyPost = new FormBody.Builder()
                .add("a", a)
                .add("b", b)
                .build();
         Request requestPost = new Request.Builder()
                .url("https://www.google.com.tw/"+a+b)
                .post(requestBodyPost)
                .build();
        client.newCall(requestPost).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("Debug"," post----------onFailure--->");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
             //   final String string = response.body().string();
             //okhttp的锅…response.body().string()中的string()方法只能调用一次……….坑死
                String html = new String(response.body().bytes(), "big5");
               

            }
        });

    }

reycleview 寬高問題,item高度設置

//reycleview  item高度設置
class SpaceItemDecoration extends RecyclerView.ItemDecoration {
    int mSpace;
    /**
     * Retrieve any offsets for the given item. Each field of <code>outRect</code> specifies
     * the number of pixels that the item view should be inset by, similar to padding or margin.
     * The default implementation sets the bounds of outRect to 0 and returns.
     * <p>
     * <p>
     * If this ItemDecoration does not affect the positioning of item views, it should set
     * all four fields of <code>outRect</code> (left, top, right, bottom) to zero
     * before returning.
     * <p>
     * <p>
     * If you need to access Adapter for additional data, you can call
     * {@link RecyclerView#getChildAdapterPosition(View)} to get the adapter position of the
     * View.
     *
     * @param outRect Rect to receive the output.
     * @param view    The child view to decorate
     * @param parent  RecyclerView this ItemDecoration is decorating
     * @param state   The current state of RecyclerView.
     */
    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        super.getItemOffsets(outRect, view, parent, state);
        outRect.left = mSpace;
        outRect.right = mSpace;
        outRect.bottom = mSpace;
        if (parent.getChildAdapterPosition(view) == 0) {
            outRect.top = mSpace;
        }

    }

    public SpaceItemDecoration(int space) {
        this.mSpace = space;
    }
}

使用:
  recyclerView.addItemDecoration(new SpaceItemDecoration(5)); 可以設定 item 與 item之間的高度

//-------------------------------------------------------------------------------------------------------------

 RecyclerView的item的宽高问题
            View view = LayoutInflater.from(context).inflate(R.layout.test_test,null);
            上面的做法就会出问题

            改成这样就可以正常显示设置的宽高
            View view = LayoutInflater.from(context).inflate(R.layout.test_test,parent,false);

自訂義的Toash

 
 public static void showToast(final Activity activity, final String word, final long time){
        activity.runOnUiThread(new Runnable() {
            public void run() {
                final Toast toast = Toast.makeText(activity, word, Toast.LENGTH_LONG);
                toast.show();
                Handler handler = new Handler();
                handler.postDelayed(new Runnable() {
                    public void run() {
                        toast.cancel();
                    }
                }, time);
            }
        });
    }

Sock 创建客户端 & 服务器的连接


      public void connet(){
        // 步骤1:创建客户端 & 服务器的连接
        // 创建Socket对象 & 指定服务端的IP及端口号
        try {
            socket=new Socket(); 
            socket   = new Socket("192.168.10.14", 55555);
            socket.setSoTimeout(1000); //設超時
            socket.isConnected();  
            Log.e("Debug","連接"+ socket.isConnected());
            Toast.makeText(this, "連接"+socket.isConnected(), Toast.LENGTH_SHORT).show();
            if( socket.isConnected()){
                two();
            }
        } catch (IOException e) {
            Log.e("Debug","IOException"+ socket.isConnected());
            Toast.makeText(this, "IOException"+socket.isConnected(), Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        }
        // 判断客户端和服务器是否连接成功
    }


   //   <-- 操作2:发送数据 到 服务器 -->
   
第一種方式
    public void sennd1(){
        //   <-- 操作2:发送数据 到 服务器 -->
        // 步骤1:从Socket 获得输出流对象OutputStream
        // 该对象作用:发送数据
        OutputStream outputStream = null;
        try {
            outputStream = socket.getOutputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 步骤2:写入需要发送的数据到输出流对象中 
        for(int i = 0 ; i < 5 ; i++){
            try {
                outputStream.write(("Carson_Ho"+i+"\n").getBytes("utf-8"));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        // 特别注意:数据的结尾加上换行符才可让服务器端的readline()停止阻塞
        // 步骤3:发送数据到服务端
        try {
        outputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            // 步骤3:断开客户端 & 服务器 连接
             outputStream.close();
            // 断开 客户端发送到服务器 的连接,即关闭输出流对象OutputStream
            br.close();
            // 断开 服务器发送到客户端 的连接,即关闭输入流读取器对象BufferedReader
            socket.close();
            // 最终关闭整个Socket连接
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

第二種方式 
 
   public void sennd2(){ 
        //   <-- 操作2:发送数据 到 服务器 -->
        // 步骤1:从Socket 获得输出流对象OutputStream
        // 该对象作用:发送数据 
        // 步骤2:写入需要发送的数据到输出流对象中
        try {
            //向服务器端发送数据
            Map<String, String> map = new HashMap<String, String>();
            map.put("name","aa");
            map.put("img","bb");
            map.put("op","cc"+"");
            JSONObject json = new JSONObject(map);
            String jsonString = "";
            jsonString = json.toString(); 
            //将String转化为byte[]
            //byte[] jsonByte = new byte[jsonString.length()+1];
            byte[] jsonByte = jsonString.getBytes();
            DataOutputStream outputStream = null;
            outputStream = new DataOutputStream(socket.getOutputStream());
            System.out.println("发的数据长度为:"+jsonByte.length);
            outputStream.write(jsonByte);
            outputStream.flush();
            System.out.println("传输数据完毕");
            socket.shutdownOutput();

            Toast.makeText(this, "Carson_ho", Toast.LENGTH_SHORT).show();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

public void service(){
        // <-- 操作1:接收服务器的数据 -->
        // 步骤1:创建输入流对象InputStream
        InputStream is = null;
        try {
            is = socket.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 步骤2:创建输入流读取器对象 并传入输入流对象
        // 该对象作用:获取服务器返回的数据
        InputStreamReader isr = new InputStreamReader(is);
        BufferedReader br = new BufferedReader(isr);

        // 步骤3:通过输入流读取器对象 接收服务器发送过来的数据
        try {
            br.readLine();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

2018年8月11日 星期六

okhttp 設置 big5


      @Override
      public void onResponse(Call call, Response response) throws IOException {
//             final String string = response.body().string();
                byte[] b = response.body().bytes(); //获取数据的bytes
               String info = new String(b, "Big5"); //然后将其转为Big5
             }
        }); 
 or 
            @Override
            public void onResponse(Call call, Response response) throws IOException {
             //   final String string = response.body().string();
            //okhttp…response.body().string()中的string()方法只能调用一次………. 
              String html = new String(response.body().bytes(), "big5");  //轉 big5

            }
        });
 -------------------------------------------------------------
okhttp异常
java.lang.IllegalStateException: closed
okhttp3.internal.http.Http1xStream$ChunkedSource.read(Http1xStream.java:418)
okhttp …response.body().string()中的string()方法只能调用一次 

2018年8月2日 星期四

算两个时间差(精确到毫秒)

     
Java中计算两个时间差(精确到毫秒)
 SimpleDateFormat dfs = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
        long between = 0;
        try {
            java.util.Date begin = dfs.parse("2009-07-10 10:22:21.214");
            java.util.Date end = dfs.parse("2009-07-20 11:24:49.145");
            between = (end.getTime() - begin.getTime());// 得到两者的毫秒数
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        long day = between / (24 * 60 * 60 * 1000);
        long hour = (between / (60 * 60 * 1000) - day * 24);
        long min = ((between / (60 * 1000)) - day * 24 * 60 - hour * 60);
        long s = (between / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60);
        long ms = (between - day * 24 * 60 * 60 * 1000 - hour * 60 * 60 * 1000
                - min * 60 * 1000 - s * 1000);
        System.out.println(day + "天" + hour + "小时" + min + "分" + s + "秒" + ms
                + "毫秒");



-----------------------------------------------------------------------------------------------------------

android 計算時間相差
Date dateStart = format.parse(info.stratTime);
Date dateEnd = format.parse(info.endTime);
//date.getTime()所返回的是一个long型的毫秒数
Long time = (Long) ((dateEnd.getTime() - dateStart.getTime())/1000);
int second = (int) (time % 60); 
int minute = (int) (time / 60 % 60);
int hour = (int) (time / 60 / 60);
texts[0] += "  " + hour + "時" + minute + "分" + second + "秒";