Example usage for android.content Context openFileOutput

List of usage examples for android.content Context openFileOutput

Introduction

In this page you can find the example usage for android.content Context openFileOutput.

Prototype

public abstract FileOutputStream openFileOutput(String name, @FileMode int mode) throws FileNotFoundException;

Source Link

Document

Open a private file associated with this Context's application package for writing.

Usage

From source file:RhodesService.java

private File downloadPackage(String url) throws IOException {
    final Context ctx = RhodesActivity.getContext();

    final Thread thisThread = Thread.currentThread();

    final Runnable cancelAction = new Runnable() {
        public void run() {
            thisThread.interrupt();//  ww w .  j  a v  a  2  s.  com
        }
    };

    BroadcastReceiver downloadReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(ACTION_ASK_CANCEL_DOWNLOAD)) {
                AlertDialog.Builder builder = new AlertDialog.Builder(ctx);
                builder.setMessage("Cancel download?");
                AlertDialog dialog = builder.create();
                dialog.setButton(AlertDialog.BUTTON_POSITIVE, ctx.getText(android.R.string.yes),
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                cancelAction.run();
                            }
                        });
                dialog.setButton(AlertDialog.BUTTON_NEGATIVE, ctx.getText(android.R.string.no),
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                // Nothing
                            }
                        });
                dialog.show();
            } else if (action.equals(ACTION_CANCEL_DOWNLOAD)) {
                cancelAction.run();
            }
        }
    };
    IntentFilter filter = new IntentFilter();
    filter.addAction(ACTION_ASK_CANCEL_DOWNLOAD);
    filter.addAction(ACTION_CANCEL_DOWNLOAD);
    ctx.registerReceiver(downloadReceiver, filter);

    File tmpFile = null;
    InputStream is = null;
    OutputStream os = null;
    try {
        updateDownloadNotification(url, -1, 0);

        /*
        List<File> folders = new ArrayList<File>();
        folders.add(Environment.getDownloadCacheDirectory());
        folders.add(Environment.getDataDirectory());
        folders.add(ctx.getCacheDir());
        folders.add(ctx.getFilesDir());
        try {
           folders.add(new File(ctx.getPackageManager().getApplicationInfo(ctx.getPackageName(), 0).dataDir));
        } catch (NameNotFoundException e1) {
           // Ignore
        }
        folders.add(Environment.getExternalStorageDirectory());
                
        for (File folder : folders) {
           File tmpRootFolder = new File(folder, "rhodownload");
           File tmpFolder = new File(tmpRootFolder, ctx.getPackageName());
           if (tmpFolder.exists())
              deleteFilesInFolder(tmpFolder.getAbsolutePath());
           else
              tmpFolder.mkdirs();
                   
           File of = new File(tmpFolder, UUID.randomUUID().toString() + ".apk");
           Logger.D(TAG, "Check path " + of.getAbsolutePath() + "...");
           try {
              os = new FileOutputStream(of);
           }
           catch (FileNotFoundException e) {
              Logger.D(TAG, "Can't open file " + of.getAbsolutePath() + ", check next path");
              continue;
           }
           Logger.D(TAG, "File " + of.getAbsolutePath() + " succesfully opened for write, start download app");
                   
           tmpFile = of;
           break;
        }
        */

        tmpFile = ctx.getFileStreamPath(UUID.randomUUID().toString() + ".apk");
        os = ctx.openFileOutput(tmpFile.getName(), Context.MODE_WORLD_READABLE);

        Logger.D(TAG, "Download " + url + " to " + tmpFile.getAbsolutePath() + "...");

        URL u = new URL(url);
        URLConnection conn = u.openConnection();
        int totalBytes = -1;
        if (conn instanceof HttpURLConnection) {
            HttpURLConnection httpConn = (HttpURLConnection) conn;
            totalBytes = httpConn.getContentLength();
        }
        is = conn.getInputStream();

        int downloaded = 0;
        updateDownloadNotification(url, totalBytes, downloaded);

        long prevProgress = 0;
        byte[] buf = new byte[65536];
        for (;;) {
            if (thisThread.isInterrupted()) {
                tmpFile.delete();
                Logger.D(TAG, "Download of " + url + " was canceled");
                return null;
            }
            int nread = is.read(buf);
            if (nread == -1)
                break;

            //Logger.D(TAG, "Downloading " + url + ": got " + nread + " bytes...");
            os.write(buf, 0, nread);

            downloaded += nread;
            if (totalBytes > 0) {
                // Update progress view only if current progress is greater than
                // previous by more than 10%. Otherwise, if update it very frequently,
                // user will no have chance to click on notification view and cancel if need
                long progress = downloaded * 10 / totalBytes;
                if (progress > prevProgress) {
                    updateDownloadNotification(url, totalBytes, downloaded);
                    prevProgress = progress;
                }
            }
        }

        Logger.D(TAG, "File stored to " + tmpFile.getAbsolutePath());

        return tmpFile;
    } catch (IOException e) {
        if (tmpFile != null)
            tmpFile.delete();
        throw e;
    } finally {
        try {
            if (is != null)
                is.close();
        } catch (IOException e) {
        }
        try {
            if (os != null)
                os.close();
        } catch (IOException e) {
        }

        mNM.cancel(DOWNLOAD_PACKAGE_ID);
        ctx.unregisterReceiver(downloadReceiver);
    }
}

From source file:cn.ttyhuo.view.UserView.java

public void setupViews(JSONObject jsonObject, final Context context) throws JSONException {

    JSONObject jObject;/*from w w  w . j a v a  2s .c om*/
    if (jsonObject.has("user"))
        jObject = jsonObject.getJSONObject("user");
    else
        jObject = jsonObject.getJSONObject("userWithLatLng");

    String userStatus = JSONUtil.getStringFromJson(jObject, "status", "");
    if (!userStatus.equals("")) {
        if (tv_userStatus != null)
            tv_userStatus.setText("(" + userStatus + ")");
    } else {
        if (tv_userStatus != null)
            tv_userStatus.setText("");
    }

    if (tv_userTypeStr != null)
        tv_userTypeStr.setText(JSONUtil.getStringFromJson(jsonObject, "userTypeStr", ""));

    String userName = JSONUtil.getStringFromJson(jObject, "userName", "??");
    String imgUrl = JSONUtil.getStringFromJson(jObject, "imgUrl", "");
    int verifyFlag = 0;
    if (JSONUtil.getBoolFromJson(jObject, "sfzVerify")) {
        verifyFlag = 1;
        iv_userVerify.setVisibility(View.VISIBLE);
        imgUrl = JSONUtil.getStringFromJson(jObject, "faceImgUrl", imgUrl);
        userName = JSONUtil.getStringFromJson(jObject, "identityName", userName);
    } else {
        iv_userVerify.setVisibility(View.GONE);
    }
    tv_userName.setText(userName);

    int gender = JSONUtil.getIntFromJson(jsonObject, "gender", 0);
    if (gender == 2) {
        iv_gender.setImageResource(R.drawable.icon_nv_big);
        ll_gender.setBackgroundResource(R.drawable.bg_nv);
    } else if (gender == 1) {
        iv_gender.setImageResource(R.drawable.icon_nan_big);
        ll_gender.setBackgroundResource(R.drawable.bg_nan);
    } else {
        //TODO:??
    }

    Integer age = JSONUtil.getIntFromJson(jsonObject, "age", 0);
    tv_userAge.setText(age.toString());

    double lat = JSONUtil.getDoubleFromJson(jObject, "lat", 0.0);
    double lng = JSONUtil.getDoubleFromJson(jObject, "lng", 0.0);

    String distance = ((MyApplication) ((Activity) context).getApplication()).getDistance(lat, lng);

    //TODO:
    tv_lastPlace.setText(distance + "km");
    JSONUtil.setValueFromJson(tv_lastTime, jObject, "latlngDate", "");
    if (tv_mobileNo != null) {
        String mobileNo = JSONUtil.getStringFromJson(jObject, "mobileNo", "");
        if (mobileNo.length() > 7) {
            mobileNo = mobileNo.substring(0, 3) + "****" + mobileNo.substring(7);
        }
        tv_mobileNo.setText(mobileNo);
    }

    int thumbUpCount = jObject.getInt("thumbUpCount");
    int favoriteUserCount = jObject.getInt("favoriteUserCount");
    boolean alreadyFavorite = jObject.getBoolean("alreadyFavorite");
    final int userID = jObject.getInt("userID");

    setFavoriteAndThumbUp(userID, thumbUpCount, favoriteUserCount, alreadyFavorite, context, jObject);

    if (JSONUtil.getBoolFromJson(jsonObject, "hasProduct")) {
        iv_hasProduct.setVisibility(View.GONE);
        tv_hasProduct.setVisibility(View.VISIBLE);

        View.OnClickListener theClick = new View.OnClickListener() {
            //  ? ?
            @Override
            public void onClick(View v) {
                switch (v.getId()) {
                case R.id.iv_hasProduct:
                case R.id.tv_hasProduct:
                    Intent intent = new Intent(context, MainPage.class);
                    intent.putExtra("contentFragment", "UserProductFragment");
                    intent.putExtra("windowTitle", "?");
                    intent.putExtra("hasWindowTitle", true);
                    intent.putExtra("extraID", userID);
                    context.startActivity(intent);
                    break;

                default:
                    break;
                }
            }
        };
        iv_hasProduct.setOnClickListener(theClick);
        tv_hasProduct.setOnClickListener(theClick);
    } else {
        iv_hasProduct.setVisibility(View.GONE);
        tv_hasProduct.setVisibility(View.GONE);
    }

    verifyFlag = setupTruckInfo(context, jObject, jsonObject, verifyFlag);

    if (fl_title != null) {
        JSONUtil.setFieldValueFromJson(fl_title, jsonObject, "title", "");
        JSONUtil.setFieldValueFromJson(fl_description, jsonObject, "description", "");
        JSONUtil.setFieldValueFromJson(fl_hobby, jsonObject, "hobby", "");
        JSONUtil.setFieldValueFromJson(fl_homeTown, jsonObject, "homeTown", "");
        JSONUtil.setFieldValueFromJson(fl_createDate, jObject, "createDate", "");
    }

    verifyFlag = setupCompanyInfo(jsonObject, jObject, verifyFlag);

    setupUserVerifyImg(jObject, verifyFlag);

    setupFaceImg(context, imgUrl);

    if (iv_qrcode != null) {
        Map<String, String> params = new HashMap<String, String>();
        StringBuilder buf = new StringBuilder("http://qr.liantu.com/api.php");
        params.put("text", "http://ttyh.aliapp.com/mvc/viewUser_" + userID);
        params.put("bg", "ffffff");
        params.put("fg", "cc0000");
        params.put("fg", "gc0000");
        params.put("el", "h");
        params.put("w", "300");
        params.put("m", "10");
        params.put("pt", "00ff00");
        params.put("inpt", "000000");
        params.put("logo", "http://ttyh-document.oss-cn-qingdao.aliyuncs.com/ic_launcher.jpg");
        try {
            // GET?URL
            if (params != null && !params.isEmpty()) {
                buf.append("?");
                for (Map.Entry<String, String> entry : params.entrySet()) {
                    buf.append(entry.getKey()).append("=").append(URLEncoder.encode(entry.getValue(), "UTF-8"))
                            .append("&");
                }
                buf.deleteCharAt(buf.length() - 1);
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        final String qrcodeUrl = buf.toString();
        ImageLoader.getInstance().displayImage(qrcodeUrl, iv_qrcode, new DisplayImageOptions.Builder()
                .resetViewBeforeLoading(true).cacheInMemory(true).cacheOnDisc(true).build());

        iv_qrcode.setOnClickListener(new View.OnClickListener() {
            //  ? ?
            @Override
            public void onClick(View v) {
                try {
                    FileOutputStream fos = context.openFileOutput("qrcode.png", Context.MODE_WORLD_READABLE);
                    FileInputStream fis = new FileInputStream(
                            ImageLoader.getInstance().getDiscCache().get(qrcodeUrl));
                    byte[] buf = new byte[1024];
                    int len = 0;
                    while ((len = fis.read(buf)) != -1) {
                        fos.write(buf, 0, len);
                    }
                    fis.close();
                    fos.close();
                    shareMsg(context, "?", "?",
                            "??: ",
                            context.getFileStreamPath("qrcode.png"));
                } catch (Exception e) {
                    e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
                }
            }
        });
    }

    final String mobile = JSONUtil.getStringFromJson(jObject, "mobileNo", "");
    if (!mobile.isEmpty()) {
        if (tv_footer_call_btn != null) {
            tv_footer_call_btn.setOnClickListener(new View.OnClickListener() {
                //  ? ?
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent();
                    intent.setAction("android.intent.action.CALL");
                    intent.setData(Uri.parse("tel:" + mobile));//mobile??????
                    context.startActivity(intent);
                }
            });
        }

        if (iv_phoneIcon != null) {
            iv_phoneIcon.setOnClickListener(new View.OnClickListener() {
                //  ? ?
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent();
                    intent.setAction("android.intent.action.CALL");
                    intent.setData(Uri.parse("tel:" + mobile));//mobile??????
                    context.startActivity(intent);
                }
            });
        }
    } else {
        if (tv_footer_call_btn != null)
            tv_footer_call_btn.setOnClickListener(null);
        if (iv_phoneIcon != null)
            iv_phoneIcon.setOnClickListener(null);
    }
}

From source file:com.codename1.impl.android.AndroidImplementation.java

public static void writeServiceProperties(Context a) {
    if (servicePropertiesDirty()) {
        Map<String, String> out = getServiceProperties(a);

        for (String key : servicePropertyKeys) {

            String val = Display.getInstance().getProperty(key, null);
            if (val != null) {
                out.put(key, val);
            }//  w w w . j a  v a 2  s . c o  m
            if ("true".equals(Display.getInstance().getProperty(key + "#delete", null))) {
                out.remove(key);

            }
        }

        OutputStream os = null;
        try {
            os = a.openFileOutput("CN1$AndroidServiceProperties", 0);
            if (os == null) {
                System.out.println("Failed to save service properties null output stream");
                return;
            }
            DataOutputStream dos = new DataOutputStream(os);
            dos.writeInt(out.size());
            for (String key : out.keySet()) {
                dos.writeUTF(key);
                dos.writeUTF((String) out.get(key));
            }
            serviceProperties = null;
        } catch (FileNotFoundException ex) {
            System.out.println(
                    "Service properties file not found.  This is normal for the first run.   On subsequent runs, the file should exist.");
        } catch (IOException ex) {

            Logger.getLogger(AndroidImplementation.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                if (os != null)
                    os.close();
            } catch (Throwable ex) {
                Logger.getLogger(AndroidImplementation.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
}

From source file:com.codename1.impl.android.AndroidImplementation.java

public static void appendNotification(String type, String body, String image, String category, Context a) {
    try {/*from   ww w .j  av  a  2  s .c  o m*/
        String[] fileList = a.fileList();
        byte[] data = null;
        for (int iter = 0; iter < fileList.length; iter++) {
            if (fileList[iter].equals("CN1$AndroidPendingNotifications")) {
                InputStream is = a.openFileInput("CN1$AndroidPendingNotifications");
                if (is != null) {
                    data = readInputStream(is);
                    sCleanup(a);
                    break;
                }
            }
        }
        DataOutputStream os = new DataOutputStream(a.openFileOutput("CN1$AndroidPendingNotifications", 0));
        if (data != null) {
            data[0]++;
            os.write(data);
        } else {
            os.writeByte(1);
        }
        String bodyType = type;
        if (image != null || category != null) {
            type = "99";
        }
        if (type != null) {
            os.writeBoolean(true);
            os.writeUTF(type);
        } else {
            os.writeBoolean(false);
        }
        if ("99".equals(type)) {
            String msg = "body=" + java.net.URLEncoder.encode(body, "UTF-8") + "&type="
                    + java.net.URLEncoder.encode(bodyType, "UTF-8");
            if (category != null) {
                msg += "&category=" + java.net.URLEncoder.encode(category, "UTF-8");
            }
            if (image != null) {
                image += "&image=" + java.net.URLEncoder.encode(image, "UTF-8");
            }
            os.writeUTF(msg);

        } else {
            os.writeUTF(body);
        }
        os.writeLong(System.currentTimeMillis());
    } catch (IOException err) {
        err.printStackTrace();
    }
}