Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> 設置聯系人頭像的圖片

設置聯系人頭像的圖片

編輯:關於Android編程

icon  = (ImageView) findViewById(R.id.icon);
        icon.setBackgroundResource(R.drawable.icos6);
       
        icon.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                Display display = getWindowManager().getDefaultDisplay();
                View popupWview = getLayoutInflater().inflate(R.layout.activity_getPhoto, null);
                final PopupWindow alert = new PopupWindow(popupWview,
                        display.getWidth(),LinearLayout.LayoutParams.WRAP_CONTENT, true);
                alert.showAtLocation(v, Gravity.BOTTOM, 0, 0);

                LinearLayout touxiang = (LinearLayout) popupWview
                        .findViewById(R.id.touxiang);
                alert.setFocusable(true);
              touxiang.setOnKeyListener(new OnKeyListener() {

                    public boolean onKey(View v, int keyCode, KeyEvent event) {

                        if (event.getAction() == KeyEvent.ACTION_DOWN
                                && keyCode == KeyEvent.KEYCODE_BACK)
                            alert.dismiss();
                        return false;
                    }

                });
                Button paizhao = (Button) popupWview
                        .findViewById(R.id.paizhao);
                paizhao.setOnClickListener(new OnClickListener() {

                    public void onClick(View v) {
                        try {
                            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                            File out = new File(Environment.getExternalStorageDirectory(),"camera.jpg");
                            Uri uri = Uri.fromFile(out);
                            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
                            startActivityForResult(intent, 0);
                            } catch (Exception e) {
                            e.printStackTrace();
                            }
                         alert.dismiss();
                    }
                });
                Button xiangce = (Button) popupWview
                        .findViewById(R.id.xiangce);
                congxiangcehuoqu.setOnClickListener(new OnClickListener() {

                    public void onClick(View v) {
                        Intent intent = new Intent();
                        intent.setType("image/*");
                        intent.setAction(Intent.ACTION_GET_CONTENT);
                        /* 取得相片後返回本畫面 */
                        startActivityForResult(intent, 2);
                        alert.dismiss();
                    }
                });
                Button quxiao = (Button) popupWview
                        .findViewById(R.id.quxiao);
                quxiao.setOnClickListener(new OnClickListener() {

                    public void onClick(View v) {
                        alert.dismiss();
                    }
                });
            }
        });
        File f = new File(Environment.getExternalStorageDirectory()+"/photo/icon/");
    
        if (!f.exists()) {
            f.mkdirs();
        }
        Bitmap bitmap = null; 
        File myCaptureFile;
        try 
        { 
            myCaptureFile = new File(Environment.getExternalStorageDirectory()+"/photo/icon/friend.jpg");
            if(myCaptureFile.exists()) 
            {
                bitmap = BitmapFactory.decodeFile(Environment.getExternalStorageDirectory()+"/photo/icon/friend.jpg");
                icon.setImageBitmap(bitmap);
            }
            else{
                icon.setImageResource(R.drawable.icos6);
            }
        } catch (Exception e) 
        { 
            // TODO: handle exception 
        }
        face = VpnApplication.mUserSettings.getString(UserInfo.PHONE_VFRIEND_ICON,"0");
      
        new asynicon().execute();
       
    }
    public class asynicon extends AsyncTask<String,Integer,String>{
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            if(null != bit){
            icon.setImageBitmap(bit);
            }else{
                icon.setImageResource(R.drawable.icos6);
            }
            LogWrapper.d("aaa","圖片貼上");
            icon.invalidate();
           
        }

        @Override
        protected String doInBackground(String... params) {
            if(!face.equals("0")){
                LogWrapper.d("aaa","運行Thread方法");
                myface(face);
            }
            return null;
        }
       
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        try {
            if (requestCode==0) {
                File file = new File(Environment.getExternalStorageDirectory().toString(),"camera.jpg");
                Uri uri = Uri.fromFile(file);
                //Uri uri =  data.getData();
                Intent intent = new Intent("com.android.camera.action.CROP");
                intent.setDataAndType(uri, "image/*");
                //下面這個crop=true是設置在開啟的Intent中設置顯示的VIEW可裁剪
                intent.putExtra("crop", "true");
                // aspectX aspectY 是寬高的比例
                intent.putExtra("aspectX", 1);
                intent.putExtra("aspectY", 1);
                // outputX outputY 是裁剪圖片寬高
                intent.putExtra("outputX", 150);
                intent.putExtra("outputY", 150);
                intent.putExtra("return-data", true);
                startActivityForResult(intent, 3);
                return;
            }
            if (requestCode==2) {
                Uri uri = data.getData();
                Intent intent = new Intent("com.android.camera.action.CROP");
                intent.setDataAndType(uri, "image/*");
                //下面這個crop=true是設置在開啟的Intent中設置顯示的VIEW可裁剪
                intent.putExtra("crop", "true");
                // aspectX aspectY 是寬高的比例
                intent.putExtra("aspectX", 1);
                intent.putExtra("aspectY", 1);
                // outputX outputY 是裁剪圖片寬高
                intent.putExtra("outputX", 150);
                intent.putExtra("outputY", 150);
                intent.putExtra("return-data", true);
                startActivityForResult(intent, 3);
                return;
            }else if(requestCode == 3)
                Log.d("requestCode","requestCode == 3");
            if(data != null){
                Log.d("data","data!=null");
                setPicToView(data);
            }
        } catch (Exception e) {
        }
    }
    public  String uploadFile(String actionUrl, String fileName,
            File uploadFile) {
       
        String end = "\r\n";
        String twoHyphens = "--";
        String boundary = "*****";
        StringBuilder sb = new StringBuilder();
        String line = null;
        try {
            URL url = new URL(actionUrl);
            if(url == null){
                handler.sendEmptyMessage(4);
                return null;
            }
            HttpURLConnection httpConn = (HttpURLConnection) url
                    .openConnection();
            /* 允許Input、Output,不使用Cache */
            httpConn.setDoInput(true);
            httpConn.setDoOutput(true);
            httpConn.setUseCaches(false);
            /* 設置傳送的method=POST */
            httpConn.setRequestMethod("POST");
            /* setRequestProperty */
            httpConn.setRequestProperty("Connection", "Keep-Alive");
            httpConn.setRequestProperty("Charset", "utf-8");
            httpConn.setRequestProperty("Content-Type",
                    "multipart/form-data;boundary=" + boundary);
            /* 設置DataOutputStream */
            DataOutputStream dataOutputStream = new DataOutputStream(
                    httpConn.getOutputStream());
            dataOutputStream.writeBytes(twoHyphens + boundary + end);
            dataOutputStream.writeBytes("Content-Disposition: form-data; "
                    + "name=\"file\";filename=\""
                    + URLEncoder.encode(fileName, "utf-8") + "\"" + end);
            dataOutputStream.writeBytes(end);
            Log.d("writeBytes","Content-Disposition: form-data; "
                    + "name=\"file\";filename=\""
                    + URLEncoder.encode(fileName, "utf-8") + "\"" + end);
            /* 取得文件的FileInputStream */
            FileInputStream fileStream = new FileInputStream(uploadFile);
            /* 設置每次寫入1024bytes */
            int bufferSize = 1024;
            byte[] buffer = new byte[bufferSize];

            int length = -1;
            /* 從文件讀取數據至緩沖區 */
            while ((length = fileStream.read(buffer)) != -1) {
                /* 將資料寫入DataOutputStream中 */
                dataOutputStream.write(buffer, 0, length);
            }
            dataOutputStream.writeBytes(end);
            dataOutputStream.writeBytes(twoHyphens + boundary + twoHyphens
                    + end);

            /* close streams */
            fileStream.close();
            dataOutputStream.flush();
            BufferedReader read;
            /* 取得Response內容 */
//            InputStream resultInputStream = httpConn.getInputStream();
//            int ch;
//            StringBuffer resultBuffer = new StringBuffer();
//            while ((ch = resultInputStream.read()) != -1) {
//                resultBuffer.append((char) ch);
//            }
            read = new BufferedReader(new InputStreamReader(
                    httpConn.getInputStream(), "utf-8"));
            while ((line = read.readLine()) != null) {
                sb.append(line);
            }
            /* 關閉DataOutputStream */
            dataOutputStream.close();
            read.close();

            return sb.toString().trim();
        } catch (Exception e) {
            e.getStackTrace();
        }
        return "";
    }
    private void setPicToView(Intent picdata) {
       
        Bundle extras = picdata.getExtras();
        if (extras != null) {
            Log.d("extras","extras!=null");
            Bitmap photo = extras.getParcelable("data");
            BufferedOutputStream bos = null;
            File myCaptureFile = null;
            try {
                myCaptureFile = new File(Environment.getExternalStorageDirectory()+"/photo/icon/friend.jpg");
                if(myCaptureFile.exists()){
                    myCaptureFile.delete();
                }
                myCaptureFile.createNewFile();
                bos = new BufferedOutputStream(
                        new FileOutputStream(myCaptureFile));
                photo.compress(Bitmap.CompressFormat.JPEG,80, bos);
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }finally{
                try{
                    bos.flush();
                    bos.close();
                }catch(IOException e){

                }
            }
            File myCapture;
            try 
            { 
                myCapture = new File(Environment.getExternalStorageDirectory()+"/photo/icon/friend.jpg");
                if(myCapture.exists()) 
                {
                    Bitmap bitmap = BitmapFactory.decodeFile(Environment.getExternalStorageDirectory()+"/photo/icon/friend.jpg");
                    icon.setImageBitmap(bitmap);
                }
            } catch (Exception e) 
            { 
                // TODO: handle exception 
            }
           
            new Asyn().execute();
        }
    }
   
    public class Asyn extends AsyncTask<String,Integer,String>{
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
        }
        @Override
        protected String doInBackground(String... params) {
            // TODO Auto-generated method stub
            String code = VApplication.mUserSettings.getString("abc","0");
         
            File myCapture = new File(Environment.getExternalStorageDirectory()+"/vpn/icon/friend.jpg");
            String str = uploadFile("http://abcd/ace.php?code="+code,"friend.jpg",myCapture);
            JSONObject json;
            if(TextUtils.isEmpty(str)){
              
                return null;
            }
     
            try {
                json = new JSONObject(str);
                stateCode = json.getInt("State_code");
                msgContent = json.getString("Msg_content");
                Log.d("stateCode",String.valueOf(stateCode));
                Log.d("msgContent",msgContent);
                if(stateCode == 1){
                    myface = json.getString("myface");
                    Log.d("myface",myface);
                  
                    Editor editor = VpnApplication.mUserSettings.edit();
                    editor.putString(UserInfo.PHONE_VFRIEND_ICON,myface);
                    editor.commit();
                  
                    publishProgress(1);
                }
                handler.sendEmptyMessage(3);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }
       
    }
    public  void  myface(String face){
        URL Url = null;
        try{
            Url = new URL("http://abcd/"+face);
            if(Url!=null){
                System.out.println("實例化myfaceURL成功");
                HttpURLConnection con = (HttpURLConnection) Url.openConnection();
                con.connect();
                System.out.println("myfaceURL_HttpURLConnection實例化完成");
                InputStream in = con.getInputStream();
                System.out.println("myfaceURL:輸入流實例化完成");
                System.out.println("myfaceURL:開始讀取數據");
                bit = BitmapFactory.decodeStream(in);
                BufferedOutputStream bos = null;
                File myCaptureFile = null;
                try {
                    myCaptureFile = new File(Environment.getExternalStorageDirectory()+"/photo/icon/friend.jpg");
                    if(myCaptureFile.exists()){
                        myCaptureFile.delete();
                    }
                    myCaptureFile.createNewFile();
                    bos = new BufferedOutputStream(
                            new FileOutputStream(myCaptureFile));
                    bit.compress(Bitmap.CompressFormat.JPEG,80, bos);
                } catch (FileNotFoundException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }finally{
                    try{
                        bos.flush();
                        bos.close();
                    }catch(IOException e){

                    }
                }
               
            }
        }catch (Exception e) {
            e.getStackTrace();
        }
    }

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved