2018年11月15日 星期四

小米手機 apk安裝失敗

https://blog.csdn.net/f917386389/article/details/71079093

小米手机安装app,android studio一直提示:

DELETE_FAILED_INTERNAL_ERROR

Error while Installing APP

在MIUI 开发者选项中关闭 MIUI优化,重启手机以后,最后问题解决

允許 usb安裝應用

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);
            }
        });
    }