android.app.ProgressDialog

Here are the examples of the java api android.app.ProgressDialog taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

1276 Examples 7

19 Source : UploadActivity.java
with Apache License 2.0
from zhou-you

/**
 * <p>描述:文件上传</p>
 * 作者: zhouyou<br>
 * 日期: 2017/7/6 16:26 <br>
 * 版本: v1.0<br>
 */
public clreplaced UploadActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_upload);
    }

    private ProgressDialog dialog;

    private IProgressDialog mProgressDialog = new IProgressDialog() {

        @Override
        public Dialog getDialog() {
            if (dialog == null) {
                dialog = new ProgressDialog(UploadActivity.this);
                // 设置进度条的形式为圆形转动的进度条
                dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                dialog.setMessage("正在上传...");
                // 设置提示的replacedle的图标,默认是没有的,如果没有设置replacedle的话只设置Icon是不会显示图标的
                dialog.setreplacedle("文件上传");
                dialog.setMax(100);
            }
            return dialog;
        }
    };

    public void onUploadFile(View view) throws Exception {
        final UIProgressResponseCallBack listener = new UIProgressResponseCallBack() {

            @Override
            public void onUIResponseProgress(long bytesRead, long contentLength, boolean done) {
                int progress = (int) (bytesRead * 100 / contentLength);
                HttpLog.e(progress + "% ");
                dialog.setProgress(progress);
                dialog.setMessage(progress + "%");
                if (done) {
                    // 完成
                    dialog.setMessage("上传完整");
                }
            }
        };
        File file = new File(Environment.getExternalStorageDirectory().getPath() + "/1.jpg");
        EasyHttp.post("/v1/user/uploadAvatar").params("avatar", file, file.getName(), listener).accessToken(true).timeStamp(true).execute(new ProgressDialogCallBack<String>(mProgressDialog, true, true) {

            @Override
            public void onError(ApiException e) {
                super.onError(e);
                showToast(e.getMessage());
            }

            @Override
            public void onSuccess(String response) {
                showToast(response);
            }
        });
    }

    public void onUploadInputStream(View view) throws Exception {
        final UIProgressResponseCallBack listener = new UIProgressResponseCallBack() {

            @Override
            public void onUIResponseProgress(long bytesRead, long contentLength, boolean done) {
                int progress = (int) (bytesRead * 100 / contentLength);
                HttpLog.e(progress + "% ");
                ((ProgressDialog) mProgressDialog.getDialog()).setProgress(progress);
                if (done) {
                    // 完成
                    ((ProgressDialog) mProgressDialog.getDialog()).setMessage("上传完整");
                }
            }
        };
        final InputStream inputStream = getResources().getreplacedets().open("1.jpg");
        EasyHttp.post("/v1/user/uploadAvatar").params("avatar", inputStream, "clife.png", listener).accessToken(true).timeStamp(true).execute(new ProgressDialogCallBack<String>(mProgressDialog, true, true) {

            @Override
            public void onError(ApiException e) {
                super.onError(e);
                showToast(e.getMessage());
            }

            @Override
            public void onSuccess(String response) {
                showToast(response);
            }
        });
    }

    public void onUploadBytes(View view) throws Exception {
        final UIProgressResponseCallBack listener = new UIProgressResponseCallBack() {

            @Override
            public void onUIResponseProgress(long bytesRead, long contentLength, boolean done) {
                int progress = (int) (bytesRead * 100 / contentLength);
                HttpLog.e(progress + "% ");
                ((ProgressDialog) mProgressDialog.getDialog()).setProgress(progress);
                if (done) {
                    // 完成
                    ((ProgressDialog) mProgressDialog.getDialog()).setMessage("上传完整");
                }
            }
        };
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.test);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
        final byte[] bytes = baos.toByteArray();
        // avatar:表示key
        // bytes:表示上传的字节内容
        // "streamfile.png" 表示图片名称
        // MediaType.parse("image/*") 类型 表示上传的是图片
        // listener 上传进度回调监听
        EasyHttp.post("/v1/user/uploadAvatar").params("avatar", bytes, "streamfile.png", listener).accessToken(true).timeStamp(true).execute(new ProgressDialogCallBack<String>(mProgressDialog, true, true) {

            @Override
            public void onError(ApiException e) {
                super.onError(e);
                showToast(e.getMessage());
            }

            @Override
            public void onSuccess(String response) {
                showToast(response);
            }
        });
    }

    public void onUploadFileMaps(View view) {
        File file = new File(Environment.getExternalStorageDirectory().getPath() + "/1.jpg");
        UIProgressResponseCallBack mUIProgressResponseCallBack = new UIProgressResponseCallBack() {

            @Override
            public void onUIResponseProgress(long bytesRead, long contentLength, boolean done) {
                int progress = (int) (bytesRead * 100 / contentLength);
                HttpLog.i("progress=" + progress);
                ((ProgressDialog) mProgressDialog.getDialog()).setProgress(progress);
                if (done) {
                    // 完成
                    ((ProgressDialog) mProgressDialog.getDialog()).setMessage("上传完整");
                }
            }
        };
        EasyHttp.post("AppYuFaKu/uploadHeadImg").baseUrl("http://www.izaodao.com/Api/").params("uid", "4811420").params("auth_key", "21f8d9bcc50c6ac1ae1020ce12f5f5a7").params("avatar", file, file.getName(), mUIProgressResponseCallBack).execute(new ProgressDialogCallBack<String>(mProgressDialog, true, true) {

            @Override
            public void onSuccess(String response) {
                showToast(response);
            }

            @Override
            public void onError(ApiException e) {
                super.onError(e);
                showToast(e.getMessage());
            }
        });
    }

    public void onUploadFileMaps2(View view) {
        File file = new File(Environment.getExternalStorageDirectory().getPath() + "/1.jpg");
        UIProgressResponseCallBack mUIProgressResponseCallBack = new UIProgressResponseCallBack() {

            @Override
            public void onUIResponseProgress(long bytesRead, long contentLength, boolean done) {
                int progress = (int) (bytesRead * 100 / contentLength);
                HttpLog.i("progress=" + progress);
                ((ProgressDialog) mProgressDialog.getDialog()).setProgress(progress);
                if (done) {
                    // 完成
                    ((ProgressDialog) mProgressDialog.getDialog()).setMessage("上传完整");
                }
            }
        };
        EasyHttp.post("http://106.14.83.28:89/index.php?s=/Home/user/dj_add_care").params("uid", "1").params("replacedle", "冷小菜").params("content", "我发个哈哈哈哈哈哈哈哈").params("key", "dangjian").params("imgs[]", file, file.getName(), MediaType.parse("image/*"), mUIProgressResponseCallBack).params("imgs[]", file, file.getName(), MediaType.parse("image/*"), mUIProgressResponseCallBack).params("imgs[]", file, file.getName(), MediaType.parse("image/*"), mUIProgressResponseCallBack).execute(new ProgressDialogCallBack<String>(mProgressDialog, true, true) {

            @Override
            public void onSuccess(String response) {
                showToast(response);
            }

            @Override
            public void onError(ApiException e) {
                super.onError(e);
                showToast(e.getMessage());
            }
        });
    }

    public void onUploadOne(View view) {
        File file = new File(Environment.getExternalStorageDirectory().getPath() + "/1.jpg");
        UIProgressResponseCallBack mUIProgressResponseCallBack = new UIProgressResponseCallBack() {

            @Override
            public void onUIResponseProgress(long bytesRead, long contentLength, boolean done) {
                int progress = (int) (bytesRead * 100 / contentLength);
                HttpLog.i("progress=" + progress);
                ((ProgressDialog) mProgressDialog.getDialog()).setProgress(progress);
                if (done) {
                    // 完成
                    ((ProgressDialog) mProgressDialog.getDialog()).setMessage("上传完整");
                }
            }
        };
        EasyHttp.post("index.php/Home/index/uploadImg").baseUrl("http://106.15.42.39").params("img", file, file.getName(), mUIProgressResponseCallBack).execute(new ProgressDialogCallBack<String>(mProgressDialog, true, true) {

            @Override
            public void onSuccess(String s) {
                showToast(s);
            }

            @Override
            public void onError(ApiException e) {
                super.onError(e);
                showToast(e.getMessage());
            }
        });
    }

    private void showToast(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }
}

19 Source : DownloadActivity.java
with Apache License 2.0
from zhou-you

/**
 * <p>描述:文件下载</p>
 * 作者: zhouyou<br>
 * 日期: 2017/7/6 16:25 <br>
 * 版本: v1.0<br>
 */
public clreplaced DownloadActivity extends AppCompatActivity {

    private ProgressDialog dialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_download);
        dialog = new ProgressDialog(this);
        // 设置进度条的形式为圆形转动的进度条
        dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        dialog.setMessage("正在下载...");
        // 设置提示的replacedle的图标,默认是没有的,如果没有设置replacedle的话只设置Icon是不会显示图标的
        dialog.setreplacedle("下载文件");
        dialog.setMax(100);
    }

    public void onDownloadFile1(View view) {
        // 下载回调是在异步里处理的
        EasyHttp.downLoad("http://apk.hiapk.com/web/api.do?qt=8051&id=723").savePath(// 默认在:/storage/emulated/0/Android/data/包名/files/1494647767055
        Environment.getExternalStorageDirectory().getPath() + "/test/").saveName(// 默认名字是时间戳生成的
        "custom_name").execute(new DownloadProgressCallBack<String>() {

            @Override
            public void update(long bytesRead, long contentLength, boolean done) {
                int progress = (int) (bytesRead * 100 / contentLength);
                HttpLog.e(progress + "% ");
                dialog.setProgress(progress);
                if (done) {
                    dialog.setMessage("下载完成");
                }
            }

            @Override
            public void onStart() {
                HttpLog.i("======" + Thread.currentThread().getName());
                dialog.show();
            }

            @Override
            public void onComplete(String path) {
                showToast("文件保存路径:" + path);
                dialog.dismiss();
            }

            @Override
            public void onError(final ApiException e) {
                HttpLog.i("======" + Thread.currentThread().getName());
                showToast(e.getMessage());
                dialog.dismiss();
            }
        });
    }

    public void onDownloadFile2(View view) {
        // String url = "http://61.144.207.146:8081/b8154d3d-4166-4561-ad8d-7188a96eb195/2005/07/6c/076ce42f-3a78-4b5b-9aae-3c2959b7b1ba/kfid/2475751/qqlite_3.5.0.660_android_r108360_GuanWang_537047121_release_10000484.apk";
        // String url = "http://crfiles2.he1ju.com/0/925096f8-f720-4aa5-86ae-ef30548d2fdc.txt";
        String url = "http://txt.99dushuzu.com/download-txt/3/21068.txt";
        EasyHttp.downLoad(url).savePath(Environment.getExternalStorageDirectory().getPath() + "/test/QQ").saveName(FileUtils.getFileName(url)).execute(new DownloadProgressCallBack<String>() {

            @Override
            public void update(long bytesRead, long contentLength, boolean done) {
                int progress = (int) (bytesRead * 100 / contentLength);
                HttpLog.e(progress + "% ");
                dialog.setProgress(progress);
                if (done) {
                    dialog.setMessage("下载完成");
                }
            }

            @Override
            public void onStart() {
                dialog.show();
            }

            @Override
            public void onComplete(String path) {
                showToast("文件保存路径:" + path);
                dialog.dismiss();
            }

            @Override
            public void onError(ApiException e) {
                showToast(e.getMessage());
                dialog.dismiss();
            }
        });
    }

    private void showToast(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
    }
}

19 Source : DialogUtil.java
with Apache License 2.0
from zhonglikui

/*   public static void showShareDialog(final Activity activity, final Share share) {
           final UMShareListener umShareListener = new UMShareListener() {
               @Override
               public void onStart(SHARE_MEDIA share_media) {

               }

               @Override
               public void onResult(SHARE_MEDIA platform) {
                   // Toast.makeText(MainActivity.this, "分享成功", Toast.LENGTH_SHORT).show();
                   ToastUtil.showShort(App.getInstance().getResources().getString(R.string.share_success));
               }

               @Override
               public void onError(SHARE_MEDIA platform, Throwable t) {
                   //Toast.makeText(MainActivity.this, "分享失败", Toast.LENGTH_SHORT).show();
               }

               @Override
               public void onCancel(SHARE_MEDIA platform) {
                   //Toast.makeText(MainActivity.this, "分享取消", Toast.LENGTH_SHORT).show();
               }
           };

           final Dialog dialog = new Dialog(activity, android.R.style.Theme_Translucent_NoreplacedleBar_Fullscreen);
           View view = View.inflate(activity, R.layout.layout_share_window, null);
           view.findViewById(R.id.tv_share_to_weixin).setOnClickListener(new View.OnClickListener() {
               @Override
               public void onClick(View v) {
                   dialog.dismiss();
                   UmengManager.getInstance().toShare(activity, share, SHARE_MEDIA.WEIXIN, umShareListener);

               }
           });
           view.findViewById(R.id.tv_share_to_weixin_circle).setOnClickListener(new View.OnClickListener() {
               @Override
               public void onClick(View v) {
                   dialog.dismiss();
                   UmengManager.getInstance().toShare(activity, share, SHARE_MEDIA.WEIXIN_CIRCLE, umShareListener);

               }
           });
           view.findViewById(R.id.tv_share_to_weibo).setOnClickListener(new View.OnClickListener() {
               @Override
               public void onClick(View v) {
                   dialog.dismiss();
                   UmengManager.getInstance().toShare(activity, share, SHARE_MEDIA.SINA, umShareListener);

               }
           });
           view.findViewById(R.id.tv_share_to_qq).setOnClickListener(new View.OnClickListener() {
               @Override
               public void onClick(View v) {
                   dialog.dismiss();
                   UmengManager.getInstance().toShare(activity, share, SHARE_MEDIA.QQ, umShareListener);

               }
           });
           view.findViewById(R.id.tv_share_to_qq_zone).setOnClickListener(new View.OnClickListener() {
               @Override
               public void onClick(View v) {
                   dialog.dismiss();
                   UmengManager.getInstance().toShare(activity, share, SHARE_MEDIA.QZONE, umShareListener);
               }
           });
           //短信
           view.findViewById(R.id.tv_share_to_messaage).setOnClickListener(new View.OnClickListener() {
               @Override
               public void onClick(View v) {
                   dialog.dismiss();
                   share.setImage(null);
                   share.setFile(null);
                   Uri uri = Uri.parse("smsto:" + "");
                   Intent sendIntent = new Intent(Intent.ACTION_VIEW, uri);
                   sendIntent.putExtra("sms_body", App.getInstance().getString(R.string.sms_content));
                   activity.startActivity(sendIntent);
                   // UmengManager.getInstance().toShare(activity, share, SHARE_MEDIA.SMS, umShareListener);
               }
           });
           view.findViewById(R.id.close_btn).setOnClickListener(new View.OnClickListener() {
               @Override
               public void onClick(View v) {
                   dialog.dismiss();
               }
           });

           WindowManager.LayoutParams lp = dialog.getWindow().getAttributes();
           lp.width = ViewGroup.LayoutParams.MATCH_PARENT;
           lp.height = ViewGroup.LayoutParams.WRAP_CONTENT;
           lp.gravity = Gravity.BOTTOM;
           dialog.getWindow().setAttributes(lp);
           dialog.setContentView(view);
           dialog.setCancelable(true);
           dialog.setCanceledOnTouchOutside(true);
           dialog.show();
       }
   */
// 等待Dialog
public static ProgressDialog getProgressDialog(Activity activity, String replacedle, String message) {
    ProgressDialog dialog = new ProgressDialog(activity);
    if (!TextUtils.isEmpty(replacedle)) {
        dialog.setreplacedle(replacedle);
    }
    if (!TextUtils.isEmpty(message)) {
        dialog.setMessage(message);
    }
    return dialog;
}

19 Source : ZipRarExtractorTask.java
with Apache License 2.0
from Z-bm

public clreplaced ZipRarExtractorTask extends AsyncTask<Void, Long, Long> {

    private final String TAG = "ZipRarExtractorTask";

    private File mInput;

    private File mOutput;

    private ProgressDialog mDialog;

    private long mProgress = 0L;

    // 文件原始大小
    private long unPackSize;

    private boolean deleteZip;

    private String type;

    /**
     * @param type 压缩文件类型
     * @param original 要解压的文件完整路径
     * @param purpose 解压到哪个目录
     * @param deleteZip 解压后是否删除压缩文件
     *
     * @return This instance of ZipRarExtractorTask.
     */
    public ZipRarExtractorTask(Context context, String type, String original, String purpose, boolean deleteZip) {
        super();
        this.type = type;
        this.deleteZip = deleteZip;
        mInput = new File(original);
        mOutput = new File(purpose);
        if (!mOutput.exists()) {
            if (!mOutput.mkdirs()) {
                Log.e(TAG, "Failed to make directories:" + mOutput.getAbsolutePath());
            }
        }
        if (context != null) {
            mDialog = new ProgressDialog(context);
        } else {
            mDialog = null;
        }
    }

    @Override
    protected void onPreExecute() {
        // TODO Auto-generated method stub
        Log.d(TAG, "调用onPreExecute");
        if (mDialog != null) {
            mDialog.setreplacedle("解压中...");
            mDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "取消", new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    mDialog.cancel();
                }
            });
            mDialog.setCanceledOnTouchOutside(false);
            mDialog.setMessage(mInput.getName());
            mDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            mDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {

                @Override
                public void onCancel(DialogInterface dialog) {
                    // TODO Auto-generated method stub
                    cancel(true);
                }
            });
            mDialog.show();
        }
    }

    @Override
    protected Long doInBackground(Void... params) {
        // TODO Auto-generated method stub
        switch(type) {
            case "zip":
                return unzip();
            case "rar":
                return unRar();
            default:
                return 0L;
        }
    }

    @Override
    protected void onProgressUpdate(Long... values) {
        // TODO Auto-generated method stub
        if (mDialog == null)
            return;
        if (values.length > 1) {
            unPackSize = values[1];
            mDialog.setMax(100);
        } else
            mDialog.setProgress((int) ((double) values[0] / unPackSize * 100.0));
    }

    @Override
    protected void onPostExecute(Long result) {
        // TODO Auto-generated method stub
        if (deleteZip) {
            mInput.delete();
        }
        if (mDialog != null && mDialog.isShowing()) {
            mDialog.dismiss();
        }
        mInput = null;
        mOutput = null;
    }

    @Override
    protected void onCancelled() {
        super.onCancelled();
        mOutput.delete();
        Log.d("Extractor", "取消解压");
    }

    private long unzip() {
        long extractedSize = 0L;
        // 含有被压缩的文件对象(目录或文件)
        Enumeration<ZipEntry> entries;
        ZipFile zip = null;
        try {
            zip = new ZipFile(mInput, "GBK");
            long uncompressedSize = getOriginalSize(zip);
            publishProgress(0L, uncompressedSize);
            entries = zip.getEntries();
            while (entries.hasMoreElements()) {
                if (isCancelled())
                    break;
                ZipEntry entry = entries.nextElement();
                Log.d(TAG, "entry :" + entry.getName());
                if (entry.isDirectory()) {
                    // 目录内的文件对象会在下次遍历中会出现
                    continue;
                }
                // 每个文件的存放路径,包括文件夹内的
                File destination = new File(mOutput, entry.getName());
                if (!destination.getParentFile().exists()) {
                    Log.e(TAG, "make=" + destination.getParentFile().getAbsolutePath());
                    destination.getParentFile().mkdirs();
                }
                ProgressReportingOutputStream outStream = new ProgressReportingOutputStream(destination);
                extractedSize += save(zip.getInputStream(entry), outStream);
                outStream.close();
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            try {
                if (zip != null) {
                    zip.close();
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return extractedSize;
    }

    private long unRar() {
        long extractedSize = 0L;
        Archive rarFile = null;
        try {
            rarFile = new Archive(mInput, new UnrarCallback() {

                @Override
                public boolean isNextVolumeReady(File file) {
                    return false;
                }

                @Override
                public void volumeProgressChanged(long l, long l1) {
                    publishProgress(l);
                }
            });
            long uncompressedSize = getOriginalSize(rarFile);
            publishProgress(0L, uncompressedSize);
            for (int i = 0; i < rarFile.getFileHeaders().size(); i++) {
                if (isCancelled())
                    break;
                FileHeader fh = rarFile.getFileHeaders().get(i);
                String entryPath;
                if (fh.isUnicode()) {
                    entryPath = fh.getFileNameW().trim();
                } else {
                    entryPath = fh.getFileNameString().trim();
                }
                entryPath = entryPath.replaceAll("\\\\", "/");
                File file = new File(mOutput, entryPath);
                if (fh.isDirectory()) {
                    file.mkdirs();
                } else {
                    File parent = file.getParentFile();
                    if (parent != null && !parent.exists()) {
                        parent.mkdirs();
                    }
                    FileOutputStream fileOut = new FileOutputStream(file);
                    rarFile.extractFile(fh, fileOut);
                    fileOut.close();
                }
            }
        } catch (RarException | IOException e) {
            e.printStackTrace();
        } finally {
            if (rarFile != null) {
                try {
                    rarFile.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return extractedSize;
    }

    /**
     * @param file 压缩文件对象
     * @return 放回压缩文件的原始大小
     */
    private long getOriginalSize(ZipFile file) {
        Enumeration<ZipEntry> entries = file.getEntries();
        long originalSize = 0L;
        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            if (entry.getSize() >= 0) {
                originalSize += entry.getSize();
            }
        }
        return originalSize;
    }

    private long getOriginalSize(Archive file) {
        long originalSize = 0L;
        for (int i = 0; i < file.getFileHeaders().size(); i++) {
            FileHeader fh = file.getFileHeaders().get(i);
            if (fh.getUnpSize() >= 0) {
                originalSize += fh.getPackSize();
            }
        }
        return originalSize;
    }

    /**
     * 该方法主要是将压缩文件内的所有对象提取保存到指定路径
     * @param input  输入路
     * @param output 封装好的可以记录解压进度的输出流
     * @return 统计缓存大小
     */
    private int save(InputStream input, OutputStream output) {
        byte[] buffer = new byte[1024 * 8];
        BufferedInputStream in = new BufferedInputStream(input, 1024 * 8);
        BufferedOutputStream out = new BufferedOutputStream(output, 1024 * 8);
        int count = 0, n;
        try {
            while ((n = in.read(buffer, 0, 1024 * 8)) != -1) {
                out.write(buffer, 0, n);
                count += n;
            }
            out.flush();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            try {
                out.close();
                in.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return count;
    }

    private final clreplaced ProgressReportingOutputStream extends FileOutputStream {

        ProgressReportingOutputStream(File file) throws FileNotFoundException {
            super(file);
        // TODO Auto-generated constructor stub
        }

        @Override
        public void write(@NonNull byte[] buffer, int byteOffset, int byteCount) throws IOException {
            // TODO Auto-generated method stub
            super.write(buffer, byteOffset, byteCount);
            mProgress += byteCount;
            publishProgress(mProgress);
        }
    }
}

19 Source : IngestActivity.java
with Apache License 2.0
from yuchuangu85

private void makeProgressDialogIndeterminate() {
    ProgressDialog dialog = getProgressDialog();
    dialog.setIndeterminate(true);
}

19 Source : InitActivity.java
with MIT License
from yashketkar

public clreplaced InitActivity extends Activity {

    public static final String FROM_ME = "fromVitamioInitActivity";

    private ProgressDialog mPD;

    private UIHandler uiHandler;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        uiHandler = new UIHandler(this);
        new AsyncTask<Object, Object, Boolean>() {

            @Override
            protected void onPreExecute() {
                mPD = new ProgressDialog(InitActivity.this);
                mPD.setCancelable(false);
                mPD.setMessage(InitActivity.this.getString(getResources().getIdentifier("vitamio_init_decoders", "string", getPackageName())));
                mPD.show();
            }

            @Override
            protected void onPostExecute(Boolean inited) {
                if (inited) {
                    uiHandler.sendEmptyMessage(0);
                }
            }

            @Override
            protected Boolean doInBackground(Object... arg0) {
                // TODO Auto-generated method stub
                return null;
            }
        }.execute();
    }

    private static clreplaced UIHandler extends Handler {

        private WeakReference<Context> mContext;

        public UIHandler(Context c) {
            mContext = new WeakReference<Context>(c);
        }

        public void handleMessage(Message msg) {
            InitActivity ctx = (InitActivity) mContext.get();
            switch(msg.what) {
                case 0:
                    ctx.mPD.dismiss();
                    Intent src = ctx.getIntent();
                    Intent i = new Intent();
                    i.setClreplacedName(src.getStringExtra("package"), src.getStringExtra("clreplacedName"));
                    i.setData(src.getData());
                    i.putExtras(src);
                    i.putExtra(FROM_ME, true);
                    ctx.startActivity(i);
                    ctx.finish();
                    break;
            }
        }
    }
}

19 Source : DialogUtils.java
with Apache License 2.0
from yangchong211

/**
 * <pre>
 *     @author yangchong
 *     blog  : www.pedaily.cn
 *     time  : 2018/03/22
 *     desc  : 弹窗工具类
 *     revise:
 * </pre>
 */
public clreplaced DialogUtils {

    /**
     * 显示进度条对话框
     */
    private static ProgressDialog dialog;

    public static void showProgressDialog(Activity activity) {
        if (dialog == null) {
            dialog = new ProgressDialog(activity);
            dialog.setMessage("玩命加载中……");
            dialog.setCancelable(true);
            dialog.setCanceledOnTouchOutside(false);
        }
        dialog.show();
    }

    /**
     * 关闭进度条对话框
     */
    public static void dismissProgressDialog() {
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
        }
    }

    /**
     * 展示对话框视图,构造方法创建对象
     */
    public static CustomSelectDialog showDialog(Activity activity, CustomSelectDialog.SelectDialogListener listener, List<String> names) {
        CustomSelectDialog dialog = new CustomSelectDialog(activity, R.style.transparentFrameWindowStyle, listener, names);
        if (VideoPlayerUtils.isActivityLiving(activity)) {
            dialog.show();
        }
        return dialog;
    }
}

19 Source : TcpdumpPacketCapture.java
with MIT License
from yadavdev

/**
 * @Author: devilrx
 */
public clreplaced TcpdumpPacketCapture {

    private static Activity activity;

    private static Shell.Interactive rootTcpdumpShell;

    private static ProgressDialog progressBox;

    private static boolean isInitialised = false;

    public static void initialiseCapture(Activity _activity) {
        activity = _activity;
        progressBox = new ProgressDialog(activity);
        progressBox.setreplacedle("Initialising Capture");
        progressBox.setMessage("Please wait while packet capture is initialised...");
        progressBox.setIndeterminate(true);
        progressBox.setCancelable(false);
        progressBox.show();
        if (rootTcpdumpShell != null) {
            if (!isInitialised)
                throw new RuntimeException("rootTcpdump shell: not null, initialized:false");
            startTcpdumpCapture();
            progressBox.dismiss();
        } else {
            rootTcpdumpShell = new Shell.Builder().useSU().setWantSTDERR(false).setMinimalLogging(true).open(new Shell.OnCommandResultListener() {

                @Override
                public void onCommandResult(int commandVal, int exitVal, List<String> out) {
                    // Callback checking successful shell start.
                    if (exitVal == Shell.OnCommandResultListener.SHELL_RUNNING) {
                        isInitialised = true;
                        progressBox.setMessage("Starting packet capture..");
                        startTcpdumpCapture();
                        progressBox.dismiss();
                    } else {
                        progressBox.setMessage("There was an error starting root shell. Please grant root permissions or try again.");
                    }
                }
            });
        }
    }

    private static void startTcpdumpCapture() {
        try {
            List<String> out = Shell.SH.run("ps | grep tcpdump.bin");
            if (out.size() > 0) {
                // One process already running. Don't start another.
                ((TextView) activity.findViewById(R.id.main_tv)).setText("Tcpdump " + out.size() + " process already running at pid: " + (out.get(0).split("\\s+"))[1]);
                return;
            }
            rootTcpdumpShell.addCommand(activity.getApplicationInfo().dataDir + "/files/tcpdump.bin -w /mnt/sdcard/0001.pcap", 0, new Shell.OnCommandLineListener() {

                @Override
                public void onCommandResult(int commandVal, int exitVal) {
                    if (exitVal < 0) {
                        if (progressBox.isShowing()) {
                            progressBox.setMessage("Error returned by shell command...");
                        }
                    }
                }

                @Override
                public void onLine(String line) {
                    appendOutput(line);
                }
            });
        } catch (Exception ex) {
            ex.printStackTrace();
            throw ex;
        }
        ((TextView) activity.findViewById(R.id.main_tv)).setText("Packet capture started..");
    }

    public static int stopTcpdumpCapture(Activity _activity) {
        if (isInitialised == false) {
        // Uncommenting creates problem with sometimes main_tv output wrong. Not really required right now.
        // initialiseCapture(_activity);
        }
        if (rootTcpdumpShell == null) {
        // Not really required right now.
        // throw new RuntimeException("rootTcpdumpShell is null in: stopTcpdumpCapture.");
        }
        // Bug: Showing progress dialogue here (with above two ifs uncommented obviously) causes app to crash on "progressBox.show();"
        // if(!progressBox.isShowing())
        // progressBox.show();
        int retVal = 0;
        // progressBox.setMessage("Killing tcpdump process.");
        try {
            List<String> out = Shell.SH.run("ps | grep tcpdump.bin");
            for (String x : out) {
                String[] temp = x.split("\\s+");
                Integer pid = Integer.valueOf(temp[1]);
                List<String> exitOutput = Shell.SU.run("kill -9 " + pid.toString());
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            // retVal = -1;
            throw ex;
        }
        // progressBox.dismiss();
        return retVal;
    }

    private static void appendOutput(String line) {
        StringBuilder out = (new StringBuilder()).append(line).append((char) 10);
        ((TextView) activity.findViewById(R.id.main_tv)).append(out.toString());
    }
}

19 Source : MainActivity.java
with MIT License
from yadavdev

public clreplaced MainActivity extends AppCompatActivity {

    private ProgressDialog progressbox;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        final Button bt = (Button) findViewById(R.id.button_packet_capture);
        progressbox = new ProgressDialog(this);
        progressbox.setreplacedle("Initialising");
        progressbox.setMessage("Requesting root permissions..");
        progressbox.setIndeterminate(true);
        progressbox.setCancelable(false);
        progressbox.show();
        Runnable runnable = new Runnable() {

            @Override
            public void run() {
                final Boolean isRootAvailable = Shell.SU.available();
                Boolean processExists = false;
                String pid = null;
                if (isRootAvailable) {
                    List<String> out = Shell.SH.run("ps | grep tcpdump.bin");
                    if (out.size() == 1) {
                        processExists = true;
                        pid = (out.get(0).split("\\s+"))[1];
                    } else if (out.size() == 0) {
                        if (loadTcpdumpFromreplacedets() != 0)
                            throw new RuntimeException("Copying tcpdump binary failed.");
                    } else
                        throw new RuntimeException("Searching for running process returned unexpected result.");
                }
                final Boolean processExistsFinal = processExists;
                final String pidFinal = pid;
                runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        if (!isRootAvailable) {
                            ((TextView) findViewById(R.id.main_tv)).setText("Root permission denied or phone is not rooted!");
                            (findViewById(R.id.button_packet_capture)).setEnabled(false);
                        } else {
                            if (processExistsFinal) {
                                ((TextView) findViewById(R.id.main_tv)).setText("Tcpdump already running at pid: " + pidFinal);
                                bt.setText("Stop  Capture");
                                bt.setTag(1);
                            } else {
                                ((TextView) findViewById(R.id.main_tv)).setText("Initialization Successful.");
                                bt.setTag(0);
                            }
                        }
                    }
                });
                progressbox.dismiss();
            }
        };
        new Thread(runnable).start();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.gereplacedemId();
        // noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    public void startCapture(View v) {
        Button bt = (Button) findViewById(R.id.button_packet_capture);
        bt.setEnabled(false);
        if ((int) bt.getTag() == 1) {
            // Using progress dialogue from main. See comment in: TcpdumpPacketCapture.stopTcpdumpCapture
            progressbox.setMessage("Killing Tcpdump process.");
            progressbox.show();
            TcpdumpPacketCapture.stopTcpdumpCapture(this);
            bt.setText("Start Capture");
            bt.setTag(0);
            ((TextView) findViewById(R.id.main_tv)).setText("Packet capture stopped. Output stored in sdcard/0001.pcap.");
            progressbox.dismiss();
        } else if ((int) bt.getTag() == 0) {
            TcpdumpPacketCapture.initialiseCapture(this);
            bt.setText("Stop  Capture");
            bt.setTag(1);
        }
        bt.setEnabled(true);
    }

    public void stopAndExitActivity(View v) {
        TcpdumpPacketCapture.stopTcpdumpCapture(this);
        finish();
    }

    private int loadTcpdumpFromreplacedets() {
        int retval = 0;
        // updating progress message from other thread causes exception.
        // progressbox.setMessage("Setting up data..");
        String rootDataPath = getApplicationInfo().dataDir + "/files";
        String filePath = rootDataPath + "/tcpdump.bin";
        File file = new File(filePath);
        replacedetManager replacedetManager = getreplacedets();
        try {
            if (file.exists()) {
                Shell.SH.run("chmod 755 " + filePath);
                return retval;
            }
            new File(rootDataPath).mkdirs();
            retval = copyFileFromreplacedet(replacedetManager, "tcpdump.bin", filePath);
            // Mark the binary executable
            Shell.SH.run("chmod 755 " + filePath);
        } catch (Exception ex) {
            ex.printStackTrace();
            retval = -1;
        }
        return retval;
    }

    private int copyFileFromreplacedet(replacedetManager replacedetManager, String sourcePath, String destPath) {
        byte[] buff = new byte[1024];
        int len;
        InputStream in;
        OutputStream out;
        try {
            in = replacedetManager.open(sourcePath);
            new File(destPath).createNewFile();
            out = new FileOutputStream(destPath);
            // write file
            while ((len = in.read(buff)) != -1) {
                out.write(buff, 0, len);
            }
            in.close();
            out.flush();
            out.close();
        } catch (Exception ex) {
            ex.printStackTrace();
            return -1;
        }
        return 0;
    }
}

19 Source : HProgressDialogUtils.java
with Apache License 2.0
from xuexiangjys

/**
 * Created by Vector on 2016/8/12 0012.
 */
public clreplaced HProgressDialogUtils {

    private static ProgressDialog sHorizontalProgressDialog;

    private HProgressDialogUtils() {
        throw new UnsupportedOperationException("cannot be instantiated");
    }

    @SuppressLint("NewApi")
    public static void showHorizontalProgressDialog(Context context, String msg, boolean isShowSize) {
        cancel();
        if (sHorizontalProgressDialog == null) {
            sHorizontalProgressDialog = new ProgressDialog(context);
            sHorizontalProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            sHorizontalProgressDialog.setCancelable(false);
            if (isShowSize) {
                sHorizontalProgressDialog.setProgressNumberFormat("%2dMB/%1dMB");
            }
        }
        if (!TextUtils.isEmpty(msg)) {
            sHorizontalProgressDialog.setMessage(msg);
        }
        sHorizontalProgressDialog.show();
    }

    public static void setMax(long total) {
        if (sHorizontalProgressDialog != null) {
            sHorizontalProgressDialog.setMax(((int) total) / (1024 * 1024));
        }
    }

    public static void cancel() {
        if (sHorizontalProgressDialog != null) {
            sHorizontalProgressDialog.dismiss();
            sHorizontalProgressDialog = null;
        }
    }

    public static void setProgress(int current) {
        if (sHorizontalProgressDialog == null) {
            return;
        }
        sHorizontalProgressDialog.setProgress(current);
        if (sHorizontalProgressDialog.getProgress() >= sHorizontalProgressDialog.getMax()) {
            sHorizontalProgressDialog.dismiss();
            sHorizontalProgressDialog = null;
        }
    }

    public static void setProgress(long current) {
        if (sHorizontalProgressDialog == null) {
            return;
        }
        sHorizontalProgressDialog.setProgress(((int) current) / (1024 * 1024));
        if (sHorizontalProgressDialog.getProgress() >= sHorizontalProgressDialog.getMax()) {
            sHorizontalProgressDialog.dismiss();
            sHorizontalProgressDialog = null;
        }
    }

    public static void onLoading(long total, long current) {
        if (sHorizontalProgressDialog == null) {
            return;
        }
        if (current == 0) {
            sHorizontalProgressDialog.setMax(((int) total) / (1024 * 1024));
        }
        sHorizontalProgressDialog.setProgress(((int) current) / (1024 * 1024));
        if (sHorizontalProgressDialog.getProgress() >= sHorizontalProgressDialog.getMax()) {
            sHorizontalProgressDialog.dismiss();
            sHorizontalProgressDialog = null;
        }
    }
}

19 Source : CProgressDialogUtils.java
with Apache License 2.0
from xuexiangjys

/**
 * Created by Vector on 2016/8/12 0012.
 */
public clreplaced CProgressDialogUtils {

    private static final String TAG = CProgressDialogUtils.clreplaced.getSimpleName();

    private static ProgressDialog sCircleProgressDialog;

    private CProgressDialogUtils() {
        throw new UnsupportedOperationException("cannot be instantiated");
    }

    public static void showProgressDialog(Activity activity) {
        showProgressDialog(activity, "加载中", false, null);
    }

    public static void showProgressDialog(Activity activity, DialogInterface.OnCancelListener listener) {
        showProgressDialog(activity, "加载中", true, listener);
    }

    public static void showProgressDialog(Activity activity, String msg) {
        showProgressDialog(activity, msg, false, null);
    }

    public static void showProgressDialog(Activity activity, String msg, DialogInterface.OnCancelListener listener) {
        showProgressDialog(activity, msg, true, listener);
    }

    public static void showProgressDialog(final Activity activity, String msg, boolean cancelable, DialogInterface.OnCancelListener listener) {
        if (activity == null || activity.isFinishing()) {
            return;
        }
        if (sCircleProgressDialog == null) {
            sCircleProgressDialog = new ProgressDialog(activity);
            sCircleProgressDialog.setMessage(msg);
            sCircleProgressDialog.setOwnerActivity(activity);
            sCircleProgressDialog.setOnCancelListener(listener);
            sCircleProgressDialog.setCancelable(cancelable);
        } else {
            if (activity.equals(sCircleProgressDialog.getOwnerActivity())) {
                sCircleProgressDialog.setMessage(msg);
                sCircleProgressDialog.setCancelable(cancelable);
                sCircleProgressDialog.setOnCancelListener(listener);
            } else {
                // 不相等,所以取消任何ProgressDialog
                cancelProgressDialog();
                sCircleProgressDialog = new ProgressDialog(activity);
                sCircleProgressDialog.setMessage(msg);
                sCircleProgressDialog.setCancelable(cancelable);
                sCircleProgressDialog.setOwnerActivity(activity);
                sCircleProgressDialog.setOnCancelListener(listener);
            }
        }
        if (!sCircleProgressDialog.isShowing()) {
            sCircleProgressDialog.show();
        }
    }

    public static void cancelProgressDialog(Activity activity) {
        if (sCircleProgressDialog != null && sCircleProgressDialog.isShowing()) {
            if (sCircleProgressDialog.getOwnerActivity() == activity) {
                sCircleProgressDialog.cancel();
                sCircleProgressDialog = null;
            }
        }
    }

    public static void cancelProgressDialog() {
        if (sCircleProgressDialog != null && sCircleProgressDialog.isShowing()) {
            sCircleProgressDialog.cancel();
            sCircleProgressDialog = null;
        }
    }
}

19 Source : HProgressDialogUtils.java
with Apache License 2.0
from xuexiangjys

/**
 * @author xuexiang
 * @since 2018/8/3 下午6:47
 */
public clreplaced HProgressDialogUtils {

    private static ProgressDialog sHorizontalProgressDialog;

    private HProgressDialogUtils() {
        throw new UnsupportedOperationException("cannot be instantiated");
    }

    @SuppressLint("NewApi")
    public static void showHorizontalProgressDialog(Context context, String msg, boolean isShowSize) {
        cancel();
        if (sHorizontalProgressDialog == null) {
            sHorizontalProgressDialog = new ProgressDialog(context);
            sHorizontalProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            sHorizontalProgressDialog.setCancelable(false);
            if (isShowSize) {
                sHorizontalProgressDialog.setProgressNumberFormat("%2dMB/%1dMB");
            }
        }
        if (!TextUtils.isEmpty(msg)) {
            sHorizontalProgressDialog.setMessage(msg);
        }
        sHorizontalProgressDialog.show();
    }

    public static void setMax(long total) {
        if (sHorizontalProgressDialog != null) {
            sHorizontalProgressDialog.setMax(((int) total) / (1024 * 1024));
        }
    }

    public static void cancel() {
        if (sHorizontalProgressDialog != null) {
            sHorizontalProgressDialog.dismiss();
            sHorizontalProgressDialog = null;
        }
    }

    public static void setProgress(int current) {
        if (sHorizontalProgressDialog == null) {
            return;
        }
        sHorizontalProgressDialog.setProgress(current);
        if (sHorizontalProgressDialog.getProgress() >= sHorizontalProgressDialog.getMax()) {
            sHorizontalProgressDialog.dismiss();
            sHorizontalProgressDialog = null;
        }
    }

    public static void setProgress(long current) {
        if (sHorizontalProgressDialog == null) {
            return;
        }
        sHorizontalProgressDialog.setProgress(((int) current) / (1024 * 1024));
        if (sHorizontalProgressDialog.getProgress() >= sHorizontalProgressDialog.getMax()) {
            sHorizontalProgressDialog.dismiss();
            sHorizontalProgressDialog = null;
        }
    }

    public static void onLoading(long total, long current) {
        if (sHorizontalProgressDialog == null) {
            return;
        }
        if (current == 0) {
            sHorizontalProgressDialog.setMax(((int) total) / (1024 * 1024));
        }
        sHorizontalProgressDialog.setProgress(((int) current) / (1024 * 1024));
        if (sHorizontalProgressDialog.getProgress() >= sHorizontalProgressDialog.getMax()) {
            sHorizontalProgressDialog.dismiss();
            sHorizontalProgressDialog = null;
        }
    }
}

19 Source : ProgressDialogLoader.java
with Apache License 2.0
from xuexiangjys

/**
 * 默认进度加载
 *
 * @author xuexiang
 * @since 2018/6/10 下午9:27
 */
public clreplaced ProgressDialogLoader implements IProgressLoader {

    /**
     * 进度loading弹窗
     */
    private ProgressDialog mDialog;

    /**
     * 进度框取消监听
     */
    private OnProgressCancelListener mOnProgressCancelListener;

    public ProgressDialogLoader(Context context) {
        this(context, "请稍候...");
    }

    public ProgressDialogLoader(Context context, String msg) {
        mDialog = new ProgressDialog(context);
        updateMessage(msg);
    }

    @Override
    public boolean isLoading() {
        return mDialog != null && mDialog.isShowing();
    }

    @Override
    public void updateMessage(String msg) {
        if (mDialog != null) {
            mDialog.setMessage(msg);
        }
    }

    @Override
    public void showLoading() {
        if (mDialog != null) {
            mDialog.show();
        }
    }

    @Override
    public void dismissLoading() {
        if (mDialog != null) {
            mDialog.dismiss();
        }
    }

    @Override
    public void setCancelable(boolean flag) {
        mDialog.setCancelable(flag);
        if (flag) {
            mDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {

                @Override
                public void onCancel(DialogInterface dialogInterface) {
                    if (mOnProgressCancelListener != null) {
                        mOnProgressCancelListener.onCancelProgress();
                    }
                }
            });
        }
    }

    @Override
    public void setOnProgressCancelListener(OnProgressCancelListener listener) {
        mOnProgressCancelListener = listener;
    }
}

19 Source : ProgressDialogAsyncTask.java
with GNU General Public License v3.0
from XecureIT

public abstract clreplaced ProgressDialogAsyncTask<Params, Progress, Result> extends AsyncTask<Params, Progress, Result> {

    private final WeakReference<Context> contextReference;

    private ProgressDialog progress;

    private final String replacedle;

    private final String message;

    public ProgressDialogAsyncTask(Context context, String replacedle, String message) {
        super();
        this.contextReference = new WeakReference<>(context);
        this.replacedle = replacedle;
        this.message = message;
    }

    public ProgressDialogAsyncTask(Context context, int replacedle, int message) {
        this(context, context.getString(replacedle), context.getString(message));
    }

    @Override
    protected void onPreExecute() {
        final Context context = contextReference.get();
        if (context != null)
            progress = ProgressDialog.show(context, replacedle, message, true);
    }

    @Override
    protected void onPostExecute(Result result) {
        if (progress != null)
            progress.dismiss();
    }

    protected Context getContext() {
        return contextReference.get();
    }
}

19 Source : WalletDetailsPrivateKeysActivity.java
with Apache License 2.0
from X-CASH-official

private void recoverPrivateKeys() {
    if (wallet == null || set_wallet_preplacedword == null) {
        return;
    }
    WalletOperateManager walletOperateManager = TheApplication.getTheApplication().getWalletServiceHelper().getWalletOperateManager();
    if (walletOperateManager == null) {
        return;
    }
    Object[] objects = ProgressDialogHelp.unEnabledView(WalletDetailsPrivateKeysActivity.this, null);
    final ProgressDialog progressDialog = (ProgressDialog) objects[0];
    final String progressDialogKey = (String) objects[1];
    try {
        walletOperateManager.getWalletData(wallet.getId(), wallet.getName(), set_wallet_preplacedword, new OnWalletDataListener.Stub() {

            @Override
            public void onSuccess(final com.xcash.wallet.aidl.Wallet wallet) throws RemoteException {
                handler.post(new Runnable() {

                    @Override
                    public void run() {
                        textViewWordTips.setText(getString(R.string.activity_wallet_details_private_keys_writeDownTips_text));
                        List<KeyValueItem> keyValueItems = new ArrayList<>();
                        keyValueItems.add(new KeyValueItem(getString(R.string.activity_wallet_details_private_keys_addressKey_tips), wallet.getAddress()));
                        keyValueItems.add(new KeyValueItem(getString(R.string.activity_wallet_details_private_keys_privateViewKey_tips), wallet.getSecretViewKey()));
                        keyValueItems.add(new KeyValueItem(getString(R.string.activity_wallet_details_private_keys_privateSpendKey_tips), wallet.getSecretSpendKey()));
                        keyValueItems.add(new KeyValueItem(getString(R.string.activity_wallet_details_private_keys_publicViewKey_tips), wallet.getPublicViewKey()));
                        keyValueItems.add(new KeyValueItem(getString(R.string.activity_wallet_details_private_keys_publicSpendKey_tips), wallet.getPublicSpendKey()));
                        showPrivateKeys(linearLayoutPrivateKeys, keyValueItems);
                        ProgressDialogHelp.enabledView(WalletDetailsPrivateKeysActivity.this, progressDialog, progressDialogKey, null);
                    }
                });
            }

            @Override
            public void onError(final String error) throws RemoteException {
                handler.post(new Runnable() {

                    @Override
                    public void run() {
                        if (error != null && error.contains(ActivityHelp.SPECIFIED_FILE_EXISTS)) {
                            textViewWordTips.setText(getString(R.string.activity_create_wallet_walletExist_tips));
                        } else {
                            if (error == null) {
                                textViewWordTips.setText(getString(R.string.get_wallet_data_error_tips));
                            } else {
                                textViewWordTips.setText(error);
                            }
                        }
                        textViewWordTips.setTextColor(ContextCompat.getColor(WalletDetailsPrivateKeysActivity.this, R.color.textView_error));
                        ProgressDialogHelp.enabledView(WalletDetailsPrivateKeysActivity.this, progressDialog, progressDialogKey, null);
                    }
                });
            }
        });
    } catch (RemoteException e) {
        e.printStackTrace();
        ProgressDialogHelp.enabledView(WalletDetailsPrivateKeysActivity.this, progressDialog, progressDialogKey, null);
    }
}

19 Source : WalletDetailsMnemonicWordsActivity.java
with Apache License 2.0
from X-CASH-official

private void recoverMnemonicWords() {
    if (wallet == null || set_wallet_preplacedword == null) {
        return;
    }
    WalletOperateManager walletOperateManager = TheApplication.getTheApplication().getWalletServiceHelper().getWalletOperateManager();
    if (walletOperateManager == null) {
        return;
    }
    Object[] objects = ProgressDialogHelp.unEnabledView(WalletDetailsMnemonicWordsActivity.this, null);
    final ProgressDialog progressDialog = (ProgressDialog) objects[0];
    final String progressDialogKey = (String) objects[1];
    try {
        walletOperateManager.getWalletData(wallet.getId(), wallet.getName(), set_wallet_preplacedword, new OnWalletDataListener.Stub() {

            @Override
            public void onSuccess(final com.xcash.wallet.aidl.Wallet wallet) throws RemoteException {
                handler.post(new Runnable() {

                    @Override
                    public void run() {
                        seed = wallet.getSeed();
                        if (seed == null || seed.equals("")) {
                            textViewWordTips.setText(getString(R.string.activity_wallet_details_mnemonic_words_mnemonicEmpty_tips));
                            textViewWordTips.setTextColor(ContextCompat.getColor(WalletDetailsMnemonicWordsActivity.this, R.color.textView_error));
                        } else {
                            textViewWordTips.setText(getString(R.string.activity_wallet_details_mnemonic_words_writeDownTips_text));
                            showMnemonicWord(linearLayoutWord, seed);
                        }
                        ProgressDialogHelp.enabledView(WalletDetailsMnemonicWordsActivity.this, progressDialog, progressDialogKey, null);
                    }
                });
            }

            @Override
            public void onError(final String error) throws RemoteException {
                handler.post(new Runnable() {

                    @Override
                    public void run() {
                        if (error != null && error.contains(ActivityHelp.SPECIFIED_FILE_EXISTS)) {
                            textViewWordTips.setText(getString(R.string.activity_create_wallet_walletExist_tips));
                        } else {
                            if (error == null) {
                                textViewWordTips.setText(getString(R.string.get_wallet_data_error_tips));
                            } else {
                                textViewWordTips.setText(error);
                            }
                        }
                        textViewWordTips.setTextColor(ContextCompat.getColor(WalletDetailsMnemonicWordsActivity.this, R.color.textView_error));
                        ProgressDialogHelp.enabledView(WalletDetailsMnemonicWordsActivity.this, progressDialog, progressDialogKey, null);
                    }
                });
            }
        });
    } catch (RemoteException e) {
        e.printStackTrace();
        ProgressDialogHelp.enabledView(WalletDetailsMnemonicWordsActivity.this, progressDialog, progressDialogKey, null);
    }
}

19 Source : PaymentConfirmActivity.java
with Apache License 2.0
from X-CASH-official

private void sendTransaction() {
    WalletOperateManager walletOperateManager = TheApplication.getTheApplication().getWalletServiceHelper().getWalletOperateManager();
    if (walletOperateManager == null) {
        return;
    }
    Object[] objects = ProgressDialogHelp.unEnabledView(PaymentConfirmActivity.this, null);
    final ProgressDialog progressDialog = (ProgressDialog) objects[0];
    final String progressDialogKey = (String) objects[1];
    try {
        walletOperateManager.sendTransaction(new OnNormalListener.Stub() {

            @Override
            public void onSuccess(final String transaction) throws RemoteException {
                handler.post(new Runnable() {

                    @Override
                    public void run() {
                        BaseActivity.showShortToast(PaymentConfirmActivity.this, getString(R.string.activity_payment_confirm_paySuccess_tips));
                        ProgressDialogHelp.enabledView(PaymentConfirmActivity.this, progressDialog, progressDialogKey, null);
                        finish();
                    }
                });
            }

            @Override
            public void onError(final String error) throws RemoteException {
                handler.post(new Runnable() {

                    @Override
                    public void run() {
                        BaseActivity.showShortToast(PaymentConfirmActivity.this, error);
                        ProgressDialogHelp.enabledView(PaymentConfirmActivity.this, progressDialog, progressDialogKey, null);
                    }
                });
            }
        });
    } catch (RemoteException e) {
        e.printStackTrace();
        ProgressDialogHelp.enabledView(PaymentConfirmActivity.this, progressDialog, progressDialogKey, null);
    }
}

19 Source : ImportWalletActivity_Fragment_Keys.java
with Apache License 2.0
from X-CASH-official

private void restoreWallet() {
    if (set_wallet_name == null || set_wallet_preplacedword == null) {
        return;
    }
    final String privateViewKey = editTextPrivateViewKey.getText().toString();
    final String privateSpendKey = editTextPrivateSpendKey.getText().toString();
    final String addressKey = editTextInputAddressKey.getText().toString();
    long blockHeight = 0;
    final String blockHeightString = editTextBlockHeight.getText().toString();
    if (!blockHeightString.equals("")) {
        blockHeight = StringTool.convertStringToLong(blockHeightString);
    } else {
        final String date = textViewDate.getText().toString();
        if (!date.equals("")) {
            blockHeight = RestoreHeight.getInstance().getHeight(date);
        }
    }
    // BaseActivity.showShortToast(getBaseActivity(),getString(R.string.activity_import_wallet_fragment_quick_restore_height_tips)+blockHeight);
    WalletOperateManager walletOperateManager = TheApplication.getTheApplication().getWalletServiceHelper().getWalletOperateManager();
    if (walletOperateManager == null) {
        return;
    }
    Object[] objects = ProgressDialogHelp.unEnabledView(getBaseActivity(), null);
    final ProgressDialog progressDialog = (ProgressDialog) objects[0];
    final String progressDialogKey = (String) objects[1];
    try {
        walletOperateManager.importWalletKeys(set_wallet_name, set_wallet_preplacedword, set_wallet_description, addressKey, privateViewKey, privateSpendKey, blockHeight, new OnWalletDataListener.Stub() {

            @Override
            public void onSuccess(final com.xcash.wallet.aidl.Wallet wallet) throws RemoteException {
                handler.post(new Runnable() {

                    @Override
                    public void run() {
                        if (TheApplication.getActivityFromActivityManager(MainActivity.clreplaced.getName()) == null) {
                            Intent intent = new Intent(getBaseActivity(), MainActivity.clreplaced);
                            getBaseActivity().startActivity(intent);
                        } else {
                            MainActivity.enterAndRefreshIfActivityExist();
                        }
                        ProgressDialogHelp.enabledView(getBaseActivity(), progressDialog, progressDialogKey, null);
                    }
                });
            }

            @Override
            public void onError(final String error) throws RemoteException {
                handler.post(new Runnable() {

                    @Override
                    public void run() {
                        if (error != null && error.contains(ActivityHelp.FILE_ALREADY_EXISTS)) {
                            BaseActivity.showShortToast(getBaseActivity(), getString(R.string.activity_create_wallet_walletExist_tips));
                        } else {
                            if (error == null) {
                                BaseActivity.showShortToast(getBaseActivity(), getString(R.string.activity_create_wallet_createWalletError_tips));
                            } else {
                                BaseActivity.showShortToast(getBaseActivity(), error);
                            }
                        }
                        ProgressDialogHelp.enabledView(getBaseActivity(), progressDialog, progressDialogKey, null);
                    }
                });
            }
        });
    } catch (RemoteException e) {
        e.printStackTrace();
        ProgressDialogHelp.enabledView(getBaseActivity(), progressDialog, progressDialogKey, null);
    }
}

19 Source : DpopsRegisterActivity.java
with Apache License 2.0
from X-CASH-official

private void doRegister(final View view) {
    if (wallet == null) {
        return;
    }
    String delegateName = editTextDelegateName.getText().toString();
    if (delegateName.equals("")) {
        BaseActivity.showShortToast(DpopsRegisterActivity.this, getString(R.string.activity_dpops_register_confirmDelegateNameEmpty_tips));
        return;
    }
    String delegateIPAddress = editTextDelegateIPAddress.getText().toString();
    if (delegateIPAddress.equals("")) {
        BaseActivity.showShortToast(DpopsRegisterActivity.this, getString(R.string.activity_dpops_register_confirmDelegateIPAddressEmpty_tips));
        return;
    }
    String blockVerifierMessagesPublicKey = editTextBlockVerifierMessagesPublicKey.getText().toString();
    if (blockVerifierMessagesPublicKey.equals("")) {
        BaseActivity.showShortToast(DpopsRegisterActivity.this, getString(R.string.activity_dpops_register_confirmBlockVerifierMessagesPublicKeyEmpty_tips));
        return;
    }
    WalletOperateManager walletOperateManager = TheApplication.getTheApplication().getWalletServiceHelper().getWalletOperateManager();
    if (walletOperateManager == null) {
        return;
    }
    Object[] objects = ProgressDialogHelp.unEnabledView(DpopsRegisterActivity.this, view);
    final ProgressDialog progressDialog = (ProgressDialog) objects[0];
    final String progressDialogKey = (String) objects[1];
    try {
        final String content = "{\"delegateName\":" + delegateName + ",\"delegateIPAddress\":" + delegateIPAddress + ",\"blockVerifierMessagesPublicKey\":" + blockVerifierMessagesPublicKey + "}\n\nResult=> ";
        walletOperateManager.delegateRegister(delegateName, delegateIPAddress, blockVerifierMessagesPublicKey, new OnNormalListener.Stub() {

            @Override
            public void onSuccess(final String tips) throws RemoteException {
                WalletServiceHelper.addOperationHistory(wallet.getId(), "Delegate Register", true, content + tips);
                handler.post(new Runnable() {

                    @Override
                    public void run() {
                        textViewTips.setText(tips);
                        textViewTips.setTextColor(colorPrimary);
                        ProgressDialogHelp.enabledView(DpopsRegisterActivity.this, progressDialog, progressDialogKey, view);
                    }
                });
            }

            @Override
            public void onError(final String error) throws RemoteException {
                WalletServiceHelper.addOperationHistory(wallet.getId(), "Delegate Register", false, content + error);
                handler.post(new Runnable() {

                    @Override
                    public void run() {
                        textViewTips.setText(error);
                        textViewTips.setTextColor(textView_error);
                        ProgressDialogHelp.enabledView(DpopsRegisterActivity.this, progressDialog, progressDialogKey, view);
                    }
                });
            }
        });
    } catch (RemoteException e) {
        e.printStackTrace();
        ProgressDialogHelp.enabledView(DpopsRegisterActivity.this, progressDialog, progressDialogKey, view);
    }
}

19 Source : DpopsActivity.java
with Apache License 2.0
from X-CASH-official

private void quickToVote(String value) {
    Object[] objects = ProgressDialogHelp.unEnabledView(DpopsActivity.this, null);
    final ProgressDialog progressDialog = (ProgressDialog) objects[0];
    final String progressDialogKey = (String) objects[1];
    TheApplication.getTheApplication().getWalletServiceHelper().quickToVote(value, new WalletServiceHelper.OnVoteListener() {

        @Override
        public void onSuccess(String tips) {
            ProgressDialogHelp.enabledView(DpopsActivity.this, progressDialog, progressDialogKey, null);
        }

        @Override
        public void onError(String error) {
            ProgressDialogHelp.enabledView(DpopsActivity.this, progressDialog, progressDialogKey, null);
        }
    });
}

19 Source : CreateWalletActivity.java
with Apache License 2.0
from X-CASH-official

private void createWallet() {
    if (set_wallet_name == null || set_wallet_preplacedword == null) {
        return;
    }
    WalletOperateManager walletOperateManager = TheApplication.getTheApplication().getWalletServiceHelper().getWalletOperateManager();
    if (walletOperateManager == null) {
        return;
    }
    Object[] objects = ProgressDialogHelp.unEnabledView(CreateWalletActivity.this, null);
    final ProgressDialog progressDialog = (ProgressDialog) objects[0];
    final String progressDialogKey = (String) objects[1];
    try {
        walletOperateManager.createWallet(set_wallet_name, set_wallet_preplacedword, set_wallet_description, new OnWalletDataListener.Stub() {

            @Override
            public void onSuccess(final com.xcash.wallet.aidl.Wallet wallet) throws RemoteException {
                handler.post(new Runnable() {

                    @Override
                    public void run() {
                        seed = wallet.getSeed();
                        textViewWordTips.setText(getString(R.string.activity_create_wallet_writeDownTips_text));
                        buttonNext.setVisibility(View.VISIBLE);
                        showMnemonicWord(linearLayoutWord, seed);
                        WalletManagerActivity.doRefreshIfActivityExist();
                        MainActivity.doRefreshIfActivityExist();
                        ProgressDialogHelp.enabledView(CreateWalletActivity.this, progressDialog, progressDialogKey, null);
                    }
                });
            }

            @Override
            public void onError(final String error) throws RemoteException {
                handler.post(new Runnable() {

                    @Override
                    public void run() {
                        if (error != null && error.contains(ActivityHelp.SPECIFIED_FILE_EXISTS)) {
                            textViewWordTips.setText(getString(R.string.activity_create_wallet_walletExist_tips));
                        } else {
                            if (error == null) {
                                textViewWordTips.setText(getString(R.string.activity_create_wallet_createWalletError_tips));
                            } else {
                                textViewWordTips.setText(error);
                            }
                        }
                        textViewWordTips.setTextColor(ContextCompat.getColor(CreateWalletActivity.this, R.color.textView_error));
                        ProgressDialogHelp.enabledView(CreateWalletActivity.this, progressDialog, progressDialogKey, null);
                    }
                });
            }
        });
    } catch (RemoteException e) {
        e.printStackTrace();
        ProgressDialogHelp.enabledView(CreateWalletActivity.this, progressDialog, progressDialogKey, null);
    }
}

19 Source : BaseActivity.java
with MIT License
from wzgiceman

/**
 * Created by WZG on 2016/12/26.
 */
public clreplaced BaseActivity extends RxAppCompatActivity {

    // 加载框可自己定义
    protected ProgressDialog pd;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (pd == null) {
            pd = new ProgressDialog(this);
            pd.setCancelable(false);
        }
    }

    protected void showP() {
        if (pd != null && !pd.isShowing()) {
            pd.show();
        }
    }

    protected void dismissP() {
        if (pd != null && pd.isShowing()) {
            pd.dismiss();
        }
    }
}

19 Source : PickImageActivity.java
with Apache License 2.0
from WrBug

public clreplaced PickImageActivity extends Activity {

    private static final int REQ_PICK_IMAGE = 1;

    private static final int REQ_CROP_IMAGE = 2;

    private static final String ACTION_CROP = "com.android.camera.action.CROP";

    public static final String EXTRA_CROP = "crop";

    public static final String EXTRA_SCALE = "scale";

    public static final String EXTRA_SCALE_UP = "scaleUpIfNeeded";

    public static final String EXTRA_ASPECT_X = "aspectX";

    public static final String EXTRA_ASPECT_Y = "aspectY";

    public static final String EXTRA_OUTPUT_X = "outputX";

    public static final String EXTRA_OUTPUT_Y = "outputY";

    public static final String EXTRA_SPOTLIGHT_X = "spotlightX";

    public static final String EXTRA_SPOTLIGHT_Y = "spotlightY";

    public static final String EXTRA_FILE_PATH = "filePath";

    private ProgressDialog mProgressDialog;

    private LoadResult mLoadResult;

    private boolean mCropImage;

    private boolean mScale;

    private boolean mScaleUp;

    private Point mAspectSize;

    private Point mOutputSize;

    private Point mSpotlightSize;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mProgressDialog = new ProgressDialog(PickImageActivity.this);
        mProgressDialog.setMessage(getString(R.string.lc_please_wait));
        mProgressDialog.setIndeterminate(true);
        mProgressDialog.setCancelable(false);
        Intent startIntent = getIntent();
        if (savedInstanceState == null && startIntent != null) {
            mCropImage = startIntent.getBooleanExtra(EXTRA_CROP, false);
            mScale = startIntent.getBooleanExtra(EXTRA_SCALE, false);
            mScaleUp = startIntent.getBooleanExtra(EXTRA_SCALE_UP, false);
            if (startIntent.hasExtra(EXTRA_ASPECT_X) || startIntent.hasExtra(EXTRA_ASPECT_Y)) {
                mAspectSize = new Point(startIntent.getIntExtra(EXTRA_ASPECT_X, 0), startIntent.getIntExtra(EXTRA_ASPECT_Y, 0));
            }
            if (startIntent.hasExtra(EXTRA_OUTPUT_X) || startIntent.hasExtra(EXTRA_OUTPUT_Y)) {
                mOutputSize = new Point(startIntent.getIntExtra(EXTRA_OUTPUT_X, 0), startIntent.getIntExtra(EXTRA_OUTPUT_Y, 0));
            }
            if (startIntent.hasExtra(EXTRA_SPOTLIGHT_X) || startIntent.hasExtra(EXTRA_SPOTLIGHT_Y)) {
                mSpotlightSize = new Point(startIntent.getIntExtra(EXTRA_SPOTLIGHT_X, 0), startIntent.getIntExtra(EXTRA_SPOTLIGHT_Y, 0));
            }
            Intent intent = new Intent(Intent.ACTION_PICK);
            intent.setType("image/*");
            startActivityForResult(Intent.createChooser(intent, getString(R.string.imgpick_dialog_replacedle)), REQ_PICK_IMAGE);
        } else {
            finish();
        }
    }

    @Override
    public void onDestroy() {
        dismissProgressDialog();
        super.onDestroy();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == REQ_PICK_IMAGE) {
                new ImageLoader().execute(data.getData());
            } else if (requestCode == REQ_CROP_IMAGE) {
                new File(mLoadResult.filePath).delete();
                mLoadResult.filePath += "_cropped";
                setResult(Activity.RESULT_OK, new Intent().putExtra(EXTRA_FILE_PATH, mLoadResult.filePath));
                finish();
            }
        } else {
            setResult(Activity.RESULT_CANCELED);
            cleanup();
            finish();
        }
    }

    private void onImageLoadedResult(LoadResult result) {
        if (isDestroyed()) {
            cleanup();
            return;
        } else if (result.exception != null) {
            Toast.makeText(this, String.format("%s: %s", getString(R.string.imgpick_choose_error), result.exception.getMessage()), Toast.LENGTH_SHORT).show();
            setResult(Activity.RESULT_CANCELED);
            cleanup();
            finish();
            return;
        }
        mLoadResult = result;
        if (mCropImage) {
            cropImage();
        } else {
            setResult(Activity.RESULT_OK, new Intent().putExtra(EXTRA_FILE_PATH, mLoadResult.filePath));
            finish();
        }
    }

    private void cropImage() {
        try {
            File srcFile = new File(mLoadResult.filePath);
            Uri uri = Uri.fromFile(srcFile);
            Intent cropIntent = new Intent(ACTION_CROP);
            cropIntent.setDataAndType(uri, "image/*");
            cropIntent.putExtra("crop", "true");
            if (mAspectSize != null) {
                cropIntent.putExtra("aspectX", mAspectSize.x);
                cropIntent.putExtra("aspectY", mAspectSize.y);
            }
            if (mOutputSize != null) {
                cropIntent.putExtra("outputX", mOutputSize.x);
                cropIntent.putExtra("outputY", mOutputSize.y);
            }
            if (mSpotlightSize != null) {
                cropIntent.putExtra("spotlightX", mSpotlightSize.x);
                cropIntent.putExtra("spotlightY", mSpotlightSize.y);
            }
            cropIntent.putExtra("scale", mScale);
            cropIntent.putExtra("scaleUpIfNeeded", mScaleUp);
            cropIntent.putExtra("return-data", false);
            cropIntent.putExtra("outputFormat", Bitmap.CompressFormat.PNG.toString());
            File out = new File(getCacheDir() + "/" + srcFile.getName() + "_cropped");
            out.createNewFile();
            out.setReadable(true, false);
            out.setWritable(true, false);
            cropIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(out));
            startActivityForResult(cropIntent, REQ_CROP_IMAGE);
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(this, String.format("%s: %s", getString(R.string.imgpick_crop_error), e.getMessage()), Toast.LENGTH_SHORT).show();
            setResult(Activity.RESULT_CANCELED);
            cleanup();
            finish();
        }
    }

    private void dismissProgressDialog() {
        if (mProgressDialog != null && mProgressDialog.isShowing()) {
            mProgressDialog.dismiss();
        }
    }

    private void cleanup() {
        if (mLoadResult != null && mLoadResult.filePath != null) {
            new File(mLoadResult.filePath).delete();
            new File(mLoadResult.filePath + "_cropped").delete();
        }
        mLoadResult = null;
    }

    clreplaced LoadResult {

        String filePath;

        Exception exception;
    }

    clreplaced ImageLoader extends AsyncTask<Uri, Integer, LoadResult> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            mProgressDialog.show();
        }

        @Override
        protected LoadResult doInBackground(Uri... params) {
            File outFile = new File(getCacheDir() + "/" + UUID.randomUUID().toString());
            LoadResult result = new LoadResult();
            InputStream in = null;
            FileOutputStream out = null;
            try {
                in = getContentResolver().openInputStream(params[0]);
                out = new FileOutputStream(outFile);
                final byte[] buffer = new byte[1024];
                int read;
                while ((read = in.read(buffer)) != -1) {
                    out.write(buffer, 0, read);
                }
                out.flush();
                outFile.setReadable(true, false);
                outFile.setWritable(true, false);
                result.filePath = outFile.getAbsolutePath();
            } catch (Exception e) {
                e.printStackTrace();
                result.exception = e;
            } finally {
                try {
                    in.close();
                } catch (Exception e) {
                }
                try {
                    out.close();
                } catch (Exception e) {
                }
            }
            return result;
        }

        @Override
        protected void onPostExecute(LoadResult result) {
            dismissProgressDialog();
            onImageLoadedResult(result);
        }
    }
}

19 Source : EditVideoActivity.java
with GNU Affero General Public License v3.0
from vijai1996

public clreplaced EditVideoActivity extends AppCompatActivity implements OnTrimVideoListener {

    private ProgressDialog saveprogress;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit_video);
        if (!getIntent().hasExtra(Const.VIDEO_EDIT_URI_KEY)) {
            Toast.makeText(this, getResources().getString(R.string.video_not_found), Toast.LENGTH_SHORT).show();
            finish();
            return;
        }
        Uri videoUri = Uri.parse(getIntent().getStringExtra(Const.VIDEO_EDIT_URI_KEY));
        if (!new File(videoUri.getPath()).exists()) {
            Toast.makeText(this, getResources().getString(R.string.video_not_found), Toast.LENGTH_SHORT).show();
            finish();
            return;
        }
        K4LVideoTrimmer videoTrimmer = findViewById(R.id.videoTimeLine);
        MediaMetadataRetriever retriever = new MediaMetadataRetriever();
        // use one of overloaded setDataSource() functions to set your data source
        retriever.setDataSource(this, videoUri);
        String time = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
        int timeInMins = (((int) Long.parseLong(time)) / 1000) + 1000;
        Log.d(Const.TAG, timeInMins + "");
        File video = new File(videoUri.getPath());
        videoTrimmer.setOnTrimVideoListener(this);
        videoTrimmer.setVideoURI(videoUri);
        videoTrimmer.setMaxDuration(timeInMins);
        Log.d(Const.TAG, "Edited file save name: " + video.getAbsolutePath());
        videoTrimmer.setDestinationPath(video.getParent() + "/");
    }

    @Override
    public void getResult(Uri uri) {
        Log.d(Const.TAG, uri.getPath());
        indexFile(uri.getPath());
        this.runOnUiThread(new Runnable() {

            @Override
            public void run() {
                saveprogress = new ProgressDialog(EditVideoActivity.this);
                saveprogress.setMessage("Please wait while the video is being saved");
                saveprogress.setreplacedle("Please wait");
                saveprogress.setIndeterminate(true);
                saveprogress.show();
            }
        });
    }

    @Override
    public void cancelAction() {
        finish();
    }

    private void indexFile(String SAVEPATH) {
        // Create a new ArrayList and add the newly created video file path to it
        ArrayList<String> toBeScanned = new ArrayList<>();
        toBeScanned.add(SAVEPATH);
        String[] toBeScannedStr = new String[toBeScanned.size()];
        toBeScannedStr = toBeScanned.toArray(toBeScannedStr);
        // Request MediaScannerConnection to scan the new file and index it
        MediaScannerConnection.scanFile(this, toBeScannedStr, null, new MediaScannerConnection.OnScanCompletedListener() {

            @Override
            public void onScanCompleted(String path, Uri uri) {
                Log.i(Const.TAG, "SCAN COMPLETED: " + path);
                saveprogress.cancel();
                setResult(Const.VIDEO_EDIT_RESULT_CODE);
                finish();
            }
        });
    }
}

19 Source : PAudioRecorder.java
with GNU General Public License v3.0
from victordiaz

@PhonkClreplaced
public clreplaced PAudioRecorder extends ProtoBase {

    MediaRecorder recorder;

    ProgressDialog mProgressDialog;

    boolean showProgress = false;

    public PAudioRecorder(AppRunner appRunner) {
        super(appRunner);
        recorder = new MediaRecorder();
    }

    private void init() {
        // ContentValues values = new ContentValues(3);
        // values.put(MediaStore.MediaColumns.replacedLE, fileName);
        recorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT);
        recorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
        recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
        // recorder.setAudioEncoder(MediaRecorder.getAudioSourceMax());
        recorder.setAudioEncodingBitRate(96000);
        recorder.setAudioSamplingRate(44100);
    }

    @PhonkMethod(description = "Starts recording", example = "")
    @PhonkMethodParam(params = { "showProgressBoolean" })
    public PAudioRecorder record(String fileName) {
        init();
        recorder.setOutputFile(getAppRunner().getProject().getFullPathForFile(fileName));
        try {
            recorder.prepare();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (showProgress && getActivity() != null) {
            mProgressDialog = new ProgressDialog(getActivity());
            mProgressDialog.setreplacedle("Record!");
            mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            mProgressDialog.setButton(DialogInterface.BUTTON_POSITIVE, "Stop recording", (dialog, whichButton) -> {
                mProgressDialog.dismiss();
                stop();
            });
            mProgressDialog.setOnCancelListener(p1 -> stop());
            mProgressDialog.show();
        }
        recorder.start();
        return this;
    }

    public int amplitude() {
        return recorder.getMaxAmplitude();
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    public PAudioRecorder pause() {
        recorder.pause();
        return this;
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    public PAudioRecorder resume() {
        recorder.resume();
        return this;
    }

    @PhonkMethod(description = "Stops recording", example = "")
    @PhonkMethodParam(params = { "" })
    public void stop() {
        recorder.stop();
    }

    @Override
    public void __stop() {
        try {
            if (recorder != null) {
                recorder.stop();
                recorder.reset();
                recorder.release();
                recorder = null;
            }
        } catch (Exception e) {
        }
        if (showProgress && getActivity() != null) {
            mProgressDialog.dismiss();
            showProgress = false;
        }
    }
}

19 Source : DialogUtils.java
with GNU General Public License v3.0
from tortuvshin

/**
 * Created by turtuvshin on 8/1/17.
 */
public clreplaced DialogUtils {

    private static ProgressDialog dialog;

    private static DialogUtils instance;

    private DialogUtils() {
    }

    public static void init() {
        instance = new DialogUtils();
    }

    public static DialogUtils getInstance() {
        return instance;
    }

    public void startProgress(Context context, String message) {
        dialog = new ProgressDialog(context);
        dialog.setMessage(message);
        dialog.setCanceledOnTouchOutside(false);
        dialog.setCancelable(false);
        dialog.setIndeterminate(true);
        dialog.show();
    }

    public void stopProgress() {
        dialog.dismiss();
    }
}

19 Source : CommonUtil.java
with Apache License 2.0
from TommyLemon

/**
 * 通用操作类
 *  @author Lemon
 *  @use CommonUtil.xxxMethod(...);
 */
public clreplaced CommonUtil {

    private static final String TAG = "CommonUtil";

    public CommonUtil() {
    /* 不能实例化**/
    }

    // 电话<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    /**
     * 打电话
     *  @param context
     *  @param phone
     */
    public static void call(Activity context, String phone) {
        if (StringUtil.isNotEmpty(phone, true)) {
            Uri uri = Uri.parse("tel:" + phone.trim());
            Intent intent = new Intent(Intent.ACTION_CALL, uri);
            toActivity(context, intent);
            return;
        }
        showShortToast(context, "请先选择号码哦~");
    }

    // 电话>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    // 信息<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    /**
     * 发送信息,多号码
     *  @param context
     *  @param phoneList
     */
    public static void toMessageChat(Activity context, List<String> phoneList) {
        if (context == null || phoneList == null || phoneList.size() <= 0) {
            Log.e(TAG, "sendMessage context == null || phoneList == null || phoneList.size() <= 0 " + ">> showShortToast(context, 请先选择号码哦~); return; ");
            showShortToast(context, "请先选择号码哦~");
            return;
        }
        String phones = "";
        for (int i = 0; i < phoneList.size(); i++) {
            phones += phoneList.get(i) + ";";
        }
        toMessageChat(context, phones);
    }

    /**
     * 发送信息,单个号码
     *  @param context
     *  @param phone
     */
    public static void toMessageChat(Activity context, String phone) {
        if (context == null || StringUtil.isNotEmpty(phone, true) == false) {
            Log.e(TAG, "sendMessage  context == null || StringUtil.isNotEmpty(phone, true) == false) >> return;");
            return;
        }
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.putExtra("address", phone);
        intent.setType("vnd.android-dir/mms-sms");
        toActivity(context, intent);
    }

    // 信息>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    /**
     * 分享信息
     *  @param context
     *  @param toShare
     */
    public static void shareInfo(Activity context, String toShare) {
        if (context == null || StringUtil.isNotEmpty(toShare, true) == false) {
            Log.e(TAG, "shareInfo  context == null || StringUtil.isNotEmpty(toShare, true) == false >> return;");
            return;
        }
        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.setType("text/plain");
        intent.putExtra(Intent.EXTRA_SUBJECT, "选择分享方式");
        intent.putExtra(Intent.EXTRA_TEXT, toShare.trim());
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        toActivity(context, intent, -1);
    }

    /**
     * 发送邮件
     *  @param context
     *  @param emailAddress
     */
    public static void sendEmail(Activity context, String emailAddress) {
        if (context == null || StringUtil.isNotEmpty(emailAddress, true) == false) {
            Log.e(TAG, "sendEmail  context == null || StringUtil.isNotEmpty(emailAddress, true) == false >> return;");
            return;
        }
        Intent intent = new Intent(Intent.ACTION_SENDTO);
        // 缺少"mailto:"前缀导致找不到应用崩溃
        intent.setData(Uri.parse("mailto:" + emailAddress));
        // 最近在MIUI7上无内容导致无法跳到编辑邮箱界面
        intent.putExtra(Intent.EXTRA_TEXT, "内容");
        toActivity(context, intent, -1);
    }

    /**
     * 打开网站
     *  @param context
     *  @param webSite
     */
    public static void openWebSite(Activity context, String webSite) {
        if (context == null || StringUtil.isNotEmpty(webSite, true) == false) {
            Log.e(TAG, "openWebSite  context == null || StringUtil.isNotEmpty(webSite, true) == false >> return;");
            return;
        }
        toActivity(context, new Intent(Intent.ACTION_VIEW, Uri.parse(StringUtil.getCorrectUrl(webSite))));
    }

    /**
     * 复制文字
     *  @param context
     *  @param value
     */
    public static void copyText(Context context, String value) {
        if (context == null || StringUtil.isNotEmpty(value, true) == false) {
            Log.e(TAG, "copyText  context == null || StringUtil.isNotEmpty(value, true) == false >> return;");
            return;
        }
        ClipData cD = ClipData.newPlainText("simple text", value);
        ClipboardManager clipboardManager = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
        clipboardManager.setPrimaryClip(cD);
        showShortToast(context, "已复制\n" + value);
    }

    // 启动新Activity方法<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    /**
     * 打开新的Activity,向左滑入效果
     *  @param intent
     */
    public static void toActivity(final Activity context, final Intent intent) {
        toActivity(context, intent, true);
    }

    /**
     * 打开新的Activity
     *  @param intent
     *  @param showAnimation
     */
    public static void toActivity(final Activity context, final Intent intent, final boolean showAnimation) {
        toActivity(context, intent, -1, showAnimation);
    }

    /**
     * 打开新的Activity,向左滑入效果
     *  @param intent
     *  @param requestCode
     */
    public static void toActivity(final Activity context, final Intent intent, final int requestCode) {
        toActivity(context, intent, requestCode, true);
    }

    /**
     * 打开新的Activity
     *  @param intent
     *  @param requestCode
     *  @param showAnimation
     */
    public static void toActivity(final Activity context, final Intent intent, final int requestCode, final boolean showAnimation) {
        if (context == null || intent == null) {
            return;
        }
        context.runOnUiThread(new Runnable() {

            @Override
            public void run() {
                if (requestCode < 0) {
                    context.startActivity(intent);
                } else {
                    context.startActivityForResult(intent, requestCode);
                }
                if (showAnimation) {
                    context.overridePendingTransition(R.anim.right_push_in, R.anim.hold);
                } else {
                    context.overridePendingTransition(R.anim.null_anim, R.anim.null_anim);
                }
            }
        });
    }

    // 启动新Activity方法>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    // 显示与关闭进度弹窗方法<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    private static ProgressDialog progressDialog = null;

    /**
     * 展示加载进度条,无标题
     *  @param stringResId
     */
    public static void showProgressDialog(Activity context, int stringResId) {
        try {
            showProgressDialog(context, null, context.getResources().getString(stringResId));
        } catch (Exception e) {
            Log.e(TAG, "showProgressDialog  showProgressDialog(Context context, null, context.getResources().getString(stringResId));");
        }
    }

    /**
     * 展示加载进度条,无标题
     *  @param dialogMessage
     */
    public void showProgressDialog(Activity context, String dialogMessage) {
        showProgressDialog(context, null, dialogMessage);
    }

    /**
     * 展示加载进度条
     *  @param dialog replacedle 标题
     *  @param dialog Message 信息
     */
    public static void showProgressDialog(final Activity context, final String dialogreplacedle, final String dialogMessage) {
        if (context == null) {
            return;
        }
        context.runOnUiThread(new Runnable() {

            @Override
            public void run() {
                if (progressDialog == null) {
                    progressDialog = new ProgressDialog(context);
                }
                if (progressDialog.isShowing() == true) {
                    progressDialog.dismiss();
                }
                if (dialogreplacedle != null && !"".equals(dialogreplacedle.trim())) {
                    progressDialog.setreplacedle(dialogreplacedle);
                }
                if (dialogMessage != null && !"".equals(dialogMessage.trim())) {
                    progressDialog.setMessage(dialogMessage);
                }
                progressDialog.setCanceledOnTouchOutside(false);
                progressDialog.show();
            }
        });
    }

    /**
     * 隐藏加载进度
     */
    public static void dismissProgressDialog(Activity context) {
        if (context == null || progressDialog == null || progressDialog.isShowing() == false) {
            return;
        }
        context.runOnUiThread(new Runnable() {

            @Override
            public void run() {
                progressDialog.dismiss();
            }
        });
    }

    // 显示与关闭进度弹窗方法>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    // show short toast 方法<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    /**
     * 快捷显示short toast方法,需要long toast就用 Toast.makeText(string, Toast.LENGTH_LONG).show(); ---不常用所以这个类里不写
     *  @param context
     *  @param string
     */
    public static void showShortToast(final Context context, int stringResId) {
        try {
            showShortToast(context, context.getResources().getString(stringResId));
        } catch (Exception e) {
            Log.e(TAG, "showShortToast  context.getResources().getString(resId) >>  catch (Exception e) {" + e.getMessage());
        }
    }

    /**
     * 快捷显示short toast方法,需要long toast就用 Toast.makeText(string, Toast.LENGTH_LONG).show(); ---不常用所以这个类里不写
     *  @param string
     */
    public static void showShortToast(final Context context, final String string) {
        showShortToast(context, string, false);
    }

    /**
     * 快捷显示short toast方法,需要long toast就用 Toast.makeText(string, Toast.LENGTH_LONG).show(); ---不常用所以这个类里不写
     *  @param string
     *  @param isForceDismissProgressDialog
     */
    public static void showShortToast(final Context context, final String string, final boolean isForceDismissProgressDialog) {
        if (context == null) {
            return;
        }
        Toast.makeText(context, "" + string, Toast.LENGTH_SHORT).show();
    }

    // show short toast 方法>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    public static void startPhotoZoom(Activity context, int requestCode, String path, int width, int height) {
        startPhotoZoom(context, requestCode, Uri.fromFile(new File(path)), width, height);
    }

    /**
     * 照片裁剪
     *  @param context
     *  @param requestCode
     *  @param fromFile
     *  @param width
     *  @param height
     */
    public static void startPhotoZoom(Activity context, int requestCode, Uri fileUri, int width, int height) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(fileUri, "image/*");
        // crop为true是设置在开启的intent中设置显示的view可以剪裁
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX,outputY 是剪裁图片的宽高
        intent.putExtra("outputX", width);
        intent.putExtra("outputY", height);
        intent.putExtra("return-data", true);
        Log.i(TAG, "startPhotoZoom" + fileUri + " uri");
        toActivity(context, intent, requestCode);
    }

    /**
     * 保存照片到SD卡上面
     *  @param path
     *  @param photoName
     *  @param formSuffix
     *  @param photoBitmap
     */
    public static String savePhotoToSDCard(String path, String photoName, String formSuffix, Bitmap photoBitmap) {
        if (photoBitmap == null || StringUtil.isNotEmpty(path, true) == false || StringUtil.isNotEmpty(StringUtil.getTrimedString(photoName) + StringUtil.getTrimedString(formSuffix), true) == false) {
            Log.e(TAG, "savePhotoToSDCard photoBitmap == null || StringUtil.isNotEmpty(path, true) == false" + "|| StringUtil.isNotEmpty(photoName, true) == false) >> return null");
            return null;
        }
        if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) {
            File dir = new File(path);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            // 在指定路径下创建文件
            File photoFile = new File(path, photoName + "." + formSuffix);
            FileOutputStream fileOutputStream = null;
            try {
                fileOutputStream = new FileOutputStream(photoFile);
                if (photoBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream)) {
                    fileOutputStream.flush();
                    Log.i(TAG, "savePhotoToSDCard<<<<<<<<<<<<<<\n" + photoFile.getAbsolutePath() + "\n>>>>>>>>> succeed!");
                }
            } catch (FileNotFoundException e) {
                Log.e(TAG, "savePhotoToSDCard catch (FileNotFoundException e) {\n " + e.getMessage());
                photoFile.delete();
            // e.printStackTrace();
            } catch (IOException e) {
                Log.e(TAG, "savePhotoToSDCard catch (IOException e) {\n " + e.getMessage());
                photoFile.delete();
            // e.printStackTrace();
            } finally {
                try {
                    if (fileOutputStream != null) {
                        fileOutputStream.close();
                    }
                } catch (IOException e) {
                    Log.e(TAG, "savePhotoToSDCard } catch (IOException e) {\n " + e.getMessage());
                // e.printStackTrace();
                }
            }
            return photoFile.getAbsolutePath();
        }
        return null;
    }

    /**
     * 检测网络是否可用
     *
     * @param context
     * @return
     */
    public static boolean isNetWorkConnected(Context context) {
        if (context != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
            if (mNetworkInfo != null) {
                return mNetworkInfo.isAvailable();
            }
        }
        return false;
    }

    /**
     * 检测Sdcard是否存在
     *
     * @return
     */
    public static boolean isExitsSdcard() {
        return android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
    }

    /**
     * 获取顶层 Activity
     *  @param context
     *  @return
     */
    public static String getTopActivity(Context context) {
        ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        @SuppressWarnings("deprecation")
        List<RunningTaskInfo> runningTaskInfos = manager.getRunningTasks(1);
        return runningTaskInfos == null ? "" : runningTaskInfos.get(0).topActivity.getClreplacedName();
    }

    /**
     * 检查是否有位置权限
     *  @param context
     *  @return
     */
    public static boolean isHaveLocationPermission(Context context) {
        return isHavePermission(context, "android.permission.ACCESS_COARSE_LOCATION") || isHavePermission(context, "android.permission.ACCESS_FINE_LOCATION");
    }

    /**
     * 检查是否有权限
     *  @param context
     *  @param name
     *  @return
     */
    public static boolean isHavePermission(Context context, String name) {
        try {
            return PackageManager.PERMISSION_GRANTED == context.getPackageManager().checkPermission(name, context.getPackageName());
        } catch (Exception e) {
        // TODO: handle exception
        }
        return false;
    }
}

19 Source : MyHttpCallback.java
with Apache License 2.0
from tohodog

/*
 * Created by song on 2019/4/16.
 * 根据自己的项目对回调进行再包装
 */
public abstract clreplaced MyHttpCallback<T> extends QSHttpCallback<T> {

    protected boolean isShow = true;

    public MyHttpCallback() {
        super();
    }

    public MyHttpCallback(boolean isShow) {
        this.isShow = isShow;
    }

    public MyHttpCallback(Activity activity, boolean isShow) {
        super(activity);
        this.isShow = isShow;
    }

    @Override
    public T map(String response) throws HttpException {
        JSONObject jsonObject = JSON.parseObject(response);
        // 服务器状态码不对
        if (jsonObject.getIntValue("status") != 0) {
            throw HttpException.Custom(jsonObject.getString("msg"), response);
        }
        return parserT(jsonObject.getString("data"));
    }

    @Override
    public void onFailure(HttpException e) {
        // 可获取非200异常的参数
        String response = (String) e.getExObject();
        if (activity != null)
            Toast.makeText(activity, e.getPrompt(), Toast.LENGTH_LONG).show();
    }

    @Override
    public void onStart() {
        showProgressDialog(false);
    }

    @CallSuper
    @Override
    public void onEnd() {
        dismissProgressDialog();
    }

    protected ProgressDialog mDialog;

    /**
     * 用于显示Dialog
     */
    protected void showProgressDialog(boolean mCancelable) {
        if (isShow && mDialog == null && activity != null && !activity.isFinishing()) {
            mDialog = new ProgressDialog(activity);
            mDialog.setCancelable(mCancelable);
            if (mCancelable) {
                mDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {

                    @Override
                    public void onCancel(DialogInterface dialogInterface) {
                    }
                });
            }
            mDialog.show();
        }
    }

    protected void dismissProgressDialog() {
        if (isShow && mDialog != null && activity != null && !activity.isFinishing()) {
            mDialog.dismiss();
            mDialog = null;
        }
    }
}

19 Source : LoadingView.java
with Apache License 2.0
from TLocation

/**
 * 项目:趣租部落
 *
 * @author:location time:2018/11/9 20:37
 * description:
 */
public clreplaced LoadingView implements INetWorkLoadingView {

    private ProgressDialog dialog;

    @Override
    public void createLoadingView(Context context) {
        dialog = new ProgressDialog(context);
        dialog.setreplacedle("加载中");
    }

    @Override
    public void showLoading() {
        dialog.show();
    }

    @Override
    public void dismissLoading() {
        dialog.dismiss();
    }
}

19 Source : BaseFragment.java
with GNU General Public License v3.0
from ThirtyDegreesRay

/**
 * Created on 2017/7/18.
 *
 * @author ThirtyDegreesRay
 */
public abstract clreplaced BaseFragment<P extends IBaseContract.Presenter> extends Fragment implements IBaseContract.View {

    private final String TAG = BaseFragment.clreplaced.getSimpleName();

    @Inject
    protected P mPresenter;

    private ProgressDialog mProgressDialog;

    Unbinder unbinder;

    /**
     * fragment for viewpager
     */
    private boolean isPagerFragment = false;

    private boolean isFragmentShowed = false;

    public BaseFragment() {
    }

    @LayoutRes
    protected abstract int getLayoutId();

    protected abstract void setupFragmentComponent(AppComponent appComponent);

    protected abstract void initFragment(Bundle savedInstanceState);

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        // some page contain WebView will make default language changed
        AppUtils.updateAppLanguage(getActivity());
        View fragmentView = inflater.inflate(getLayoutId(), container, false);
        unbinder = ButterKnife.bind(this, fragmentView);
        initFragment(savedInstanceState);
        if (mPresenter != null)
            mPresenter.onViewInitialized();
        return fragmentView;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setupFragmentComponent(getAppComponent());
        if (mPresenter != null)
            mPresenter.attachView(this);
        DataAutoAccess.getData(this, savedInstanceState);
        DataAutoAccess.getData(this, getArguments());
        if (mPresenter != null)
            mPresenter.onRestoreInstanceState(getArguments());
        if (mPresenter != null)
            mPresenter.onRestoreInstanceState(savedInstanceState);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }

    @Override
    public void onViewStateRestored(@Nullable Bundle savedInstanceState) {
        super.onViewStateRestored(savedInstanceState);
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        DataAutoAccess.saveData(this, outState);
        if (mPresenter != null)
            mPresenter.onSaveInstanceState(outState);
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
        if (mPresenter != null)
            mPresenter.detachView();
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
    }

    @Override
    public void onStart() {
        super.onStart();
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onStop() {
        super.onStop();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onDetach() {
        super.onDetach();
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
        Glide.with(this).onLowMemory();
    }

    public void onFragmentShowed() {
        isFragmentShowed = true;
    }

    public void onFragmentHided() {
        isFragmentShowed = false;
    }

    protected AppApplication getAppApplication() {
        return AppApplication.get();
    }

    protected AppComponent getAppComponent() {
        return getAppApplication().getAppComponent();
    }

    @Override
    public void showLoading() {
    }

    @Override
    public void hideLoading() {
    }

    @Override
    public void showProgressDialog(String content) {
        getProgressDialog(content);
        mProgressDialog.show();
    }

    @Override
    public void dismissProgressDialog() {
        if (mProgressDialog != null) {
            mProgressDialog.dismiss();
        } else {
            throw new NullPointerException("dismissProgressDialog: can't dismiss a null dialog, must showForRepo dialog first!");
        }
    }

    @Override
    public ProgressDialog getProgressDialog(String content) {
        if (mProgressDialog == null) {
            mProgressDialog = new ProgressDialog(getActivity());
            mProgressDialog.setCancelable(false);
        }
        mProgressDialog.setMessage(content);
        return mProgressDialog;
    }

    @Override
    public void showToast(String message) {
        Toasty.normal(getActivity(), message).show();
    }

    @Override
    public void showInfoToast(String message) {
        Toasty.info(getActivity(), message).show();
    }

    @Override
    public void showSuccessToast(String message) {
        Toasty.success(getActivity(), message).show();
    }

    @Override
    public void showErrorToast(String message) {
        Toasty.error(getActivity(), message).show();
    }

    @Override
    public void showWarningToast(String message) {
        Toasty.warning(getActivity(), message).show();
    }

    @Override
    public void showTipDialog(String content) {
        new AlertDialog.Builder(getActivity()).setCancelable(true).setreplacedle("提示").setMessage(content).setCancelable(true).setPositiveButton("确定", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(@NonNull DialogInterface dialog, int which) {
                dialog.cancel();
            }
        }).show();
    }

    @Override
    public void showConfirmDialog(String msn, String replacedle, String confirmText, DialogInterface.OnClickListener confirmListener) {
        new AlertDialog.Builder(getActivity()).setCancelable(true).setreplacedle(replacedle).setMessage(msn).setCancelable(true).setPositiveButton(confirmText, confirmListener).setNegativeButton("取消", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(@NonNull DialogInterface dialog, int which) {
                dialog.cancel();
            }
        }).show();
    }

    public boolean isPagerFragment() {
        return isPagerFragment;
    }

    public BaseFragment setPagerFragment(boolean flag) {
        isPagerFragment = flag;
        return this;
    }

    public boolean isFragmentShowed() {
        return isFragmentShowed;
    }

    @Override
    public void showLoginPage() {
        getActivity().finishAffinity();
        Intent intent = new Intent(getActivity(), LoginActivity.clreplaced);
        startActivity(intent);
    }

    public void scrollToTop() {
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        return super.onOptionsItemSelected(item);
    }

    protected final void showOperationTip(@StringRes int msgResId) {
        if (getView() != null) {
            Snackbar snackbar = Snackbar.make(getView(), msgResId, Snackbar.LENGTH_INDEFINITE).setAction(R.string.ok, v -> {
            });
            snackbar.show();
        }
    }
}

19 Source : BasePresenter.java
with GNU General Public License v3.0
from ThirtyDegreesRay

private <T> HttpSubscriber<T> getHttpSubscriber(HttpObserver<T> httpObserver, ProgressDialog progressDialog) {
    if (progressDialog == null)
        return new HttpSubscriber<>(httpObserver);
    else
        return new HttpProgressSubscriber<>(progressDialog, httpObserver);
}

19 Source : DialogShower.java
with Apache License 2.0
from thinkmobiles

public final clreplaced DialogShower implements IDialogShower {

    private ProgressDialog progressDialog;

    @Override
    public void showProgress(Context _context) {
        if (progressDialog == null) {
            progressDialog = new ProgressDialog(_context);
            progressDialog.setMessage("Loading");
            progressDialog.setIndeterminate(true);
        }
        progressDialog.show();
    }

    @Override
    public void hideProgress() {
        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
    }
}

19 Source : BaseFragment.java
with Apache License 2.0
from thinkmobiles

public abstract clreplaced BaseFragment<T extends NavigationActivity> extends Fragment {

    protected T mActivity;

    private ProgressDialog progressDialog;

    @Override
    public void onAttach(Activity context) {
        super.onAttach(context);
        try {
            mActivity = (T) context;
        } catch (ClreplacedCastException e) {
            throw new RuntimeException("This fragment should have NavigationActivity instance");
        }
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        progressDialog = new ProgressDialog(getActivity());
    }

    public void showProgress(String message) {
        progressDialog.setMessage(message);
        progressDialog.show();
    }

    public void dismissProgress() {
        if (progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
    }

    public void showMessage(String message) {
        Toast.makeText(getActivity(), message, Toast.LENGTH_SHORT).show();
    }
}

19 Source : AbstractGameActivity.java
with Apache License 2.0
from Terence-D

/**
 * Copyright [2019] [Terence Doerksen]
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
public abstract clreplaced AbstractGameActivity extends AppCompatActivity implements View.OnClickListener {

    protected IScreen currentScreen;

    protected int currentApiVersion;

    protected int currentScreenId;

    protected IScreenRepository screenRepository;

    protected ProgressDialog dialog;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getIntent() != null)
            currentScreenId = getIntent().getIntExtra("screenId", 0);
        setProgressIndicator(true);
        screenRepository = new ScreenRepository(getApplicationContext());
        screenRepository.loadScreens(new IScreenRepository.LoadCallback() {

            @Override
            public void onLoaded(List<IScreen> screens) {
                screenRepository.getScreen(currentScreenId, new IScreenRepository.LoadScreenCallback() {

                    @Override
                    public void onLoaded(IScreen screen) {
                        currentScreen = screen;
                        loadScreen();
                        buildFontCache();
                        setProgressIndicator(false);
                    }
                });
            }
        });
    }

    private void buildFontCache() {
        FontCache.buildCache(this);
    }

    @SuppressLint("NewApi")
    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (currentApiVersion >= Build.VERSION_CODES.KITKAT && hasFocus) {
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
        }
    }

    protected StateListDrawable buildButtonDrawable(GICControl control) {
        Drawable primary;
        Drawable secondary;
        if (control.getPrimaryImage() == null)
            control.setPrimaryImage("");
        if (control.getSecondaryImage() == null)
            control.setSecondaryImage("");
        if (control.getPrimaryColor() != -1) {
            // color gradients
            // we don't support mixing color and otherwise
            // so if secondary is -1, make it match primary (replicate 1.3 bug)
            if (control.getSecondaryColor() == -1)
                control.setSecondaryColor(control.getPrimaryColor());
            primary = new GradientDrawable(GradientDrawable.Orientation.TOP_BOTTOM, new int[] { control.getSecondaryColor(), control.getPrimaryColor() });
            ((GradientDrawable) primary).setCornerRadius(3f);
        } else if (!control.getPrimaryImage().isEmpty()) {
            // build drawable based on path
            primary = Drawable.createFromPath(control.getPrimaryImage());
        } else if (control.getPrimaryImageResource() != -1) {
            // build based on built in resource
            primary = getButtonResource(control.getPrimaryImageResource(), control.getViewType(), true);
        } else {
            // fallback
            // color gradients
            primary = new GradientDrawable(GradientDrawable.Orientation.TOP_BOTTOM, new int[] { Color.BLACK, Color.WHITE });
            ((GradientDrawable) primary).setCornerRadius(3f);
        }
        if (control.getSecondaryColor() != -1) {
            // color gradients
            secondary = new GradientDrawable(GradientDrawable.Orientation.BOTTOM_TOP, new int[] { control.getPrimaryColor(), control.getSecondaryColor() });
            ((GradientDrawable) secondary).setCornerRadius(3f);
        } else if (!control.getSecondaryImage().isEmpty()) {
            // build drawable based on path
            secondary = Drawable.createFromPath(control.getSecondaryImage());
        } else if (control.getSecondaryImageResource() != -1) {
            // build based on built in resource
            secondary = getButtonResource(control.getSecondaryImageResource(), control.getViewType(), false);
        } else {
            // fallback
            // color gradients
            secondary = new GradientDrawable(GradientDrawable.Orientation.TOP_BOTTOM, new int[] { Color.WHITE, Color.BLACK });
            ((GradientDrawable) secondary).setCornerRadius(3f);
        }
        StateListDrawable res = new StateListDrawable();
        if (control.getViewType() == GICControl.TYPE_BUTTON || control.getViewType() == GICControl.TYPE_BUTTON_QUICK) {
            res.addState(new int[] { android.R.attr.state_pressed }, secondary);
        } else {
            res.addState(new int[] { android.R.attr.state_checked }, secondary);
        }
        res.addState(new int[] {}, primary);
        return res;
    }

    // primary is used for backwards compatability
    private Drawable getButtonResource(int resourceId, int type, boolean primary) {
        if (type == GICControl.TYPE_BUTTON || type == GICControl.TYPE_BUTTON_QUICK) {
            return getResources().getDrawable(ControlTypes.GetButtonDrawableId(resourceId, primary));
        } else {
            return getResources().getDrawable(ControlTypes.GetSwitchDrawableId(resourceId, primary));
        }
    }

    protected void addDragDrop(View view) {
    // unused
    }

    protected void loadScreen() {
        for (GICControl control : currentScreen.getControls()) {
            switch(control.getViewType()) {
                case GICControl.TYPE_BUTTON:
                case GICControl.TYPE_BUTTON_QUICK:
                    buildButton(control);
                    break;
                case GICControl.TYPE_TEXT:
                    buildText(control);
                    break;
                case GICControl.TYPE_IMAGE:
                    buildImage(control);
                    break;
                case GICControl.TYPE_SWITCH:
                    buildSwitch(control);
            }
        }
        View topLayout = findViewById(R.id.topLayout);
        Drawable background = currentScreen.getBackground();
        topLayout.setBackground(background);
    }

    protected View buildText(GICControl control) {
        AppCompatTextView view = new AppCompatTextView(AbstractGameActivity.this);
        TextViewCompat.setAutoSizeTextTypeUniformWithConfiguration(view, 24, Screen.MAX_CONTROL_SIZE, 2, TypedValue.COMPLEX_UNIT_SP);
        buildView(control, view);
        initText(view, control);
        return view;
    }

    protected View buildButton(GICControl control) {
        Button view = new Button(AbstractGameActivity.this);
        view.setBackground(buildButtonDrawable(control));
        initText(view, control);
        buildView(control, view);
        return view;
    }

    protected View buildSwitch(GICControl control) {
        ToggleButton view = new ToggleButton(AbstractGameActivity.this);
        view.setBackground(buildButtonDrawable(control));
        initText(view, control);
        view.setTextOff(view.getText());
        view.setTextOn(view.getText());
        buildView(control, view);
        return view;
    }

    protected View buildImage(GICControl control) {
        ImageView view = new ImageView(AbstractGameActivity.this);
        buildView(control, view);
        if (control.getPrimaryImage().isEmpty()) {
            view.setImageResource(R.mipmap.ic_launcher);
            resizeImageView(view, control.getWidth(), control.getHeight());
        } else {
            Drawable image = currentScreen.getImage(control.getPrimaryImage());
            view.setImageDrawable(image);
            resizeImageView(view, control.getWidth(), control.getHeight());
        }
        return view;
    }

    // init generic to all view types
    private void buildView(GICControl control, View view) {
        FrameLayout layout = findViewById(R.id.topLayout);
        FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(control.getWidth(), control.getHeight());
        layout.addView(view, lp);
        view.setX(control.getLeft());
        view.setY(control.getTop());
        view.setTag(control);
        // currentScreen.addControl(control);
        setClick(view);
        addDragDrop(view);
        view.setId(currentScreen.getNewControlId());
    }

    // initializations related to textview based controls (AppCompatTextView, Button, etc)
    private void initText(TextView view, GICControl control) {
        view.setWidth(control.getWidth());
        view.setHeight(control.getHeight());
        view.setTextColor(control.getFontColor());
        view.setTextSize(TypedValue.COMPLEX_UNIT_PX, control.getFontSize());
        view.setText(control.getText());
        setFontTypeface(view, control);
    }

    protected void setFontTypeface(TextView textView, GICControl control) {
        if (control.getFontName() == null || control.getFontName().isEmpty()) {
            textView.setTypeface(Typeface.DEFAULT);
        } else {
            if (control.getFontType() == 0) {
                textView.setTypeface(FontCache.get(control.getFontName(), this));
            } else {
                textView.setTypeface(FontCache.get(control.getFontName(), this));
            }
        }
    }

    protected void setClick(View view) {
        view.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
    }

    protected void setupFullScreen() {
        currentApiVersion = Build.VERSION.SDK_INT;
        final int flags;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
            flags = View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
        } else {
            flags = View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;
        }
        if (currentApiVersion >= Build.VERSION_CODES.KITKAT) {
            getWindow().getDecorView().setSystemUiVisibility(flags);
            final View decorView = getWindow().getDecorView();
            decorView.setOnSystemUiVisibilityChangeListener(new View.OnSystemUiVisibilityChangeListener() {

                @Override
                public void onSystemUiVisibilityChange(int visibility) {
                    if ((visibility & View.SYSTEM_UI_FLAG_FULLSCREEN) == 0) {
                        decorView.setSystemUiVisibility(flags);
                    }
                }
            });
        }
    }

    protected void resizeImageView(ImageView view, int newWidth, int newHeight) {
        FrameLayout.LayoutParams layout = new FrameLayout.LayoutParams(newWidth, newHeight);
        view.setLayoutParams(layout);
        view.invalidate();
    }

    protected void setProgressIndicator(boolean show) {
        if (show)
            showLoadingIndicator();
        else
            hideLoadingIndicator();
    }

    private void showLoadingIndicator() {
        buildLoadWindow();
        dialog.show();
    }

    private void hideLoadingIndicator() {
        buildLoadWindow();
        dialog.dismiss();
    }

    private void buildLoadWindow() {
        if (dialog == null) {
            // prepare our dialog
            dialog = new ProgressDialog(this);
            dialog.setMessage(getString(R.string.loading));
            dialog.setIndeterminate(true);
        }
    }
}

19 Source : BaseActivity.java
with Apache License 2.0
from TellH

public abstract clreplaced BaseActivity extends AppCompatActivity implements BaseView {

    protected ProgressDialog progressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(getLayoutId());
        progressDialog = new ProgressDialog(this);
        progressDialog.setCanceledOnTouchOutside(false);
        initView();
        initData(savedInstanceState);
    }

    public abstract void initData(Bundle savedInstanceState);

    public abstract void initView();

    public abstract int getLayoutId();

    @Override
    public void showOnError(String s) {
        progressDialog.dismiss();
        Note.show(s);
    }

    @Override
    public void showOnLoading() {
        progressDialog.setMessage("Loading...");
        progressDialog.show();
    }

    @Override
    public void showOnSuccess() {
        progressDialog.dismiss();
    // Note.show(getString(R.string.success_loading));
    }

    @Override
    public Context getViewContext() {
        return this;
    }
}

19 Source : BaseActivity.java
with MIT License
from swapnibble

/**
 * Created by swapnibble on 2017-08-24.
 */
public clreplaced BaseActivity extends AppCompatActivity implements MvpView {

    private ActivityComponent mActivityComponent;

    private ProgressDialog mProgressDlg;

    protected Toolbar setToolbarConfig(int toolbarId, boolean showUpIcon) {
        Toolbar toolbar = findViewById(toolbarId);
        if (null != toolbar) {
            setSupportActionBar(toolbar);
        }
        if (showUpIcon) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        }
        return toolbar;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch(item.gereplacedemId()) {
            case android.R.id.home:
                Intent upIntent = NavUtils.getParentActivityIntent(this);
                if (null != upIntent) {
                    upIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    if (NavUtils.shouldUpRecreateTask(this, upIntent)) {
                        // This activity is NOT part of this app's task, so create a new task
                        // when navigating up, with a synthesized back stack.
                        TaskStackBuilder.create(this).addNextIntentWithParentStack(upIntent).startActivities();
                    } else {
                        // This activity is part of this app's task, so simply
                        // navigate up to the logical parent activity.
                        NavUtils.navigateUpTo(this, upIntent);
                    }
                } else {
                    onBackPressed();
                }
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    public ActivityComponent getActivityComponent() {
        if (null == mActivityComponent) {
            mActivityComponent = DaggerActivityComponent.builder().activityModule(new ActivityModule(this)).appComponent(EosCommanderApp.get(this).getAppComponent()).build();
        }
        return mActivityComponent;
    }

    @TargetApi(Build.VERSION_CODES.M)
    public void requestPermissionsSafely(String[] permissions, int requestCode) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            requestPermissions(permissions, requestCode);
        }
    }

    @TargetApi(Build.VERSION_CODES.M)
    public boolean hasPermission(String permission) {
        return Build.VERSION.SDK_INT < Build.VERSION_CODES.M || checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED;
    }

    @Override
    public void showLoading(boolean show) {
        if ((null != mProgressDlg) && mProgressDlg.isShowing()) {
            mProgressDlg.cancel();
        }
        if (show) {
            mProgressDlg = UiUtils.showLoadingDialog(this);
        }
    }

    @Override
    public void onError(@StringRes int resId) {
        onError(getString(resId));
    }

    @Override
    public void onError(String message) {
        ShowResultDialog.newInstance(getString(R.string.error), message, null).show(getSupportFragmentManager());
    }

    @Override
    public void showToast(String message) {
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void showToast(@StringRes int resId) {
        Toast.makeText(this, resId, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void showResult(String resultMsg, String statusInfo) {
        ShowResultDialog.newInstance(getString(R.string.result), resultMsg, statusInfo).show(getSupportFragmentManager());
    }

    @Override
    public void hideKeyboard() {
        View view = this.getCurrentFocus();
        if (view != null) {
            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    }
}

19 Source : RegisterActivity.java
with Apache License 2.0
from stytooldex

public clreplaced RegisterActivity extends Fragment {

    private EditText ediusername;

    private EditText ediemail;

    private EditText edipreplacedword;

    private EditText edipreplacedwordTwo;

    // private ProgressDialog mProgressDialog;
    private ProgressDialog dialog;

    /**
     * 将用户与设备绑定起来
     *
     * @param user
     */
    private void bindUserIdAndDriverice(final MyUser user) {
        ;
        BmobQuery<MyUserInstallation> query = new BmobQuery<MyUserInstallation>();
        query.addWhereEqualTo("installationId", BmobInstallationManager.getInstallationId());
        query.findObjectsObservable(MyUserInstallation.clreplaced).subscribe(new Action1<List<MyUserInstallation>>() {

            @Override
            public void call(List<MyUserInstallation> installations) {
                if (installations.size() > 0) {
                    if (installations.size() > 0) {
                        MyUserInstallation myUserInstallation = installations.get(0);
                        myUserInstallation.setUid(user.getObjectId());
                        myUserInstallation.update(new UpdateListener() {

                            @Override
                            public void done(BmobException e) {
                                if (e == null) {
                                } else {
                                }
                            }
                        });
                    }
                } else {
                // toastE("后台不存在此设备Id的数据,请确认此设备Id是否正确!\n" + id);
                }
            }
        }, new Action1<Throwable>() {

            @Override
            public void call(Throwable throwable) {
            // toastE("查询设备数据失败:" + throwable.getMessage());
            }
        });
    }

    public static String getHostIP() {
        String hostIp = null;
        try {
            Enumeration nis = NetworkInterface.getNetworkInterfaces();
            InetAddress ia = null;
            while (nis.hasMoreElements()) {
                NetworkInterface ni = (NetworkInterface) nis.nextElement();
                Enumeration<InetAddress> ias = ni.getInetAddresses();
                while (ias.hasMoreElements()) {
                    ia = ias.nextElement();
                    if (ia instanceof Inet6Address) {
                        // skip ipv6
                        continue;
                    }
                    String ip = ia.getHostAddress();
                    if (!"127.0.0.1".equals(ip)) {
                        hostIp = ia.getHostAddress();
                        break;
                    }
                }
            }
        } catch (SocketException e) {
            // Log.i("yao", "SocketException");
            e.printStackTrace();
        }
        return hostIp;
    }

    @SuppressLint("HardwareIds")
    private void register() {
        String username = ediusername.getText().toString().trim();
        String email = ediemail.getText().toString().trim();
        String preplacedword = edipreplacedword.getText().toString().trim();
        String preplacedwordTwo = edipreplacedwordTwo.getText().toString().trim();
        // ediusername.setError(null);
        // ediemail.setError(null);
        // edipreplacedword.setError(null);
        // edipreplacedwordTwo.setError(null);
        if (TextUtils.isEmpty(username)) {
            // mProgressDialog.dismiss();
            ediusername.setError("用户名不能为空");
            return;
        }
        if (TextUtils.isEmpty(email)) {
            // mProgressDialog.dismiss();
            ediemail.setError("请输入邮箱");
            return;
        }
        if (!isEmailValidate(email)) {
            // mProgressDialog.dismiss();
            ediemail.setError("这不是一个有效的邮箱");
            return;
        }
        if (TextUtils.isEmpty(preplacedword)) {
            // mProgressDialog.dismiss();
            edipreplacedword.setError("密码不能为空");
            return;
        }
        if (TextUtils.isEmpty(preplacedwordTwo)) {
            // mProgressDialog.dismiss();
            edipreplacedwordTwo.setError("请再次输入一次密码");
            return;
        }
        if (!preplacedword.equals(preplacedwordTwo)) {
            // mProgressDialog.dismiss();
            Toast.makeText(getActivity(), "两次输入的密码不一致", Toast.LENGTH_SHORT).show();
            // new AlertDialog.Builder(getActivity()).setMessage("两次输入的密码不一致").create().show();
            return;
        }
        if (!isPreplacedwordValidate(preplacedword)) {
            // mProgressDialog.dismiss();
            Toast.makeText(getActivity(), "密码长度过短,最小7位以上", Toast.LENGTH_SHORT).show();
            // new AlertDialog.Builder(getActivity()).setMessage("密码长度过短,最小7位以上").create().show();
            return;
        }
        TelephonyManager tm = (TelephonyManager) getActivity().getSystemService(android.support.v4.app.FragmentActivity.TELEPHONY_SERVICE);
        final MyUser user = new MyUser();
        user.setUsername(username);
        user.setPreplacedword(preplacedword);
        user.setEmail(email);
        user.setScore(10);
        user.setSex(1);
        user.setNum("vs");
        user.setAge(1);
        user.setAddress("不激活");
        user.setHol(tm.getDeviceId());
        user.setid("520");
        user.setGender(false);
        user.setGen_(false);
        user.setGen_v(false);
        user.setPlayScore(1);
        user.setSignScore(1);
        user.setPlayScore_(1);
        user.setPlayScore_s(1);
        user.setGame("v");
        user.setCardNumber("v");
        user.setBankName("v");
        user.signUp(new SaveListener<MyUser>() {

            @Override
            public void done(MyUser s, BmobException i) {
                if (i == null) {
                    bindUserIdAndDriverice(user);
                    getActivity().finish();
                } else {
                    if (i.getErrorCode() == 202) {
                        // mProgressDialog.dismiss();
                        Toast.makeText(getActivity(), "该用户名已被注册", Toast.LENGTH_SHORT).show();
                    } else if (i.getErrorCode() == 304) {
                        // mProgressDialog.dismiss();
                        Toast.makeText(getActivity(), "其中一项输入为空", Toast.LENGTH_SHORT).show();
                    } else if (i.getErrorCode() == 9010) {
                        // mProgressDialog.dismiss();
                        Toast.makeText(getActivity(), "网络超时", Toast.LENGTH_SHORT).show();
                    } else if (i.getErrorCode() == 203) {
                        // mProgressDialog.dismiss();
                        Toast.makeText(getActivity(), "该邮箱已注册帐号,请登录", Toast.LENGTH_SHORT).show();
                    } else {
                        // mProgressDialog.dismiss();
                        Toast.makeText(getActivity(), "注册失败" + i, Toast.LENGTH_SHORT).show();
                    }
                }
            }
        });
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        final View view = inflater.inflate(R.layout.lxw_register, null);
        Toast.makeText(getActivity(), "不懂可直接加入官方群使用游客帐号\n(如登录发现闪退.可联系作者)", Toast.LENGTH_SHORT).show();
        ediusername = view.findViewById(R.id.lxw_id_reg_edi_username);
        ediemail = view.findViewById(R.id.lxw_id_reg_edi_email);
        edipreplacedword = view.findViewById(R.id.lxw_id_reg_edi_preplacedword);
        edipreplacedwordTwo = view.findViewById(R.id.lxw_id_reg_edi_preplacedword_two);
        Button btnReg = view.findViewById(R.id.lxw_id_reg_btn_register);
        btnReg.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                register();
                dialog = new ProgressDialog(getActivity());
                // 转盘
                dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
                // dialog.setCancelable(false);
                dialog.setCanceledOnTouchOutside(false);
                dialog.setreplacedle("提示");
                dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {

                    @Override
                    public void onDismiss(DialogInterface dialog) {
                    // Toast.makeText(getActivity(), "消失了", Toast.LENGTH_SHORT).show();
                    }
                });
                dialog.setMessage("<_>");
                dialog.show();
            // mProgressDialog = ProgressDialog.show(getActivity(), null, "...");
            // Toast.makeText(getActivity(), "注册帐号系统维护中,请暂时使用通用帐号", Toast.LENGTH_SHORT).show();
            }
        });
        return view;
    }

    private boolean isPreplacedwordValidate(String preplacedword) {
        return preplacedword.length() > 6;
    }

    private boolean isEmailValidate(String email) {
        return email.contains("@");
    }
}

19 Source : DialogManager.java
with Apache License 2.0
from stytooldex

/**
 * Created by lum on 2017/12/6.
 */
public clreplaced DialogManager {

    private static DialogManager mInstnce = null;

    private ProgressDialog mDialog;

    public static DialogManager getInstnce() {
        if (mInstnce == null) {
            // 线程安全模式
            synchronized (DialogManager.clreplaced) {
                if (mInstnce == null) {
                    mInstnce = new DialogManager();
                }
            }
        }
        return mInstnce;
    }

    public void showProgressDialog(Context context) {
        if (mDialog == null) {
            mDialog = new ProgressDialog(context);
            // 设置点击dialog外部,不会自动退出dialog
            mDialog.setCanceledOnTouchOutside(false);
        }
        mDialog.show();
    }

    public void dismissProgressDialog() {
        if (mDialog != null) {
            mDialog.dismiss();
        }
        mDialog = null;
    }
}

19 Source : BaseFragment.java
with Apache License 2.0
from stridercheng

/**
 * 作者:Rance on 2016/11/18 15:19
 * 邮箱:[email protected]
 */
public clreplaced BaseFragment extends Fragment {

    public Activity mActivity;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mActivity = getActivity();
        return super.onCreateView(inflater, container, savedInstanceState);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mActivity = getActivity();
    }

    public void toastShow(int resId) {
        Toast.makeText(mActivity, resId, Toast.LENGTH_SHORT).show();
    }

    public void toastShow(String resId) {
        Toast.makeText(mActivity, resId, Toast.LENGTH_SHORT).show();
    }

    public ProgressDialog progressDialog;

    public ProgressDialog showProgressDialog() {
        progressDialog = new ProgressDialog(mActivity);
        progressDialog.setMessage("加载中");
        progressDialog.show();
        return progressDialog;
    }

    public ProgressDialog showProgressDialog(CharSequence message) {
        progressDialog = new ProgressDialog(mActivity);
        progressDialog.setMessage(message);
        progressDialog.show();
        return progressDialog;
    }

    public void dismissProgressDialog() {
        if (progressDialog != null && progressDialog.isShowing()) {
            // progressDialog.hide();会导致android.view.WindowLeaked
            progressDialog.dismiss();
        }
    }
}

19 Source : SetNewPasswordAsyncTask.java
with GNU General Public License v3.0
from stingle

public clreplaced SetNewPreplacedwordAsyncTask extends AsyncTask<Void, Void, Boolean> {

    private AppCompatActivity activity;

    private String email;

    private String phrase;

    private String preplacedword;

    private Boolean localOnly;

    private OnAsyncTaskFinish onFinish;

    private ProgressDialog progressDialog;

    private boolean showProgress = true;

    private boolean uploadPrivateKey = true;

    public SetNewPreplacedwordAsyncTask(AppCompatActivity context, String email, String phrase, String preplacedword, OnAsyncTaskFinish onFinish) {
        this(context, email, phrase, preplacedword, false, onFinish);
    }

    public SetNewPreplacedwordAsyncTask(AppCompatActivity context, String email, String phrase, String preplacedword, Boolean localOnly, OnAsyncTaskFinish onFinish) {
        this.activity = context;
        this.email = email;
        this.phrase = phrase;
        this.preplacedword = preplacedword;
        this.localOnly = localOnly;
        this.onFinish = onFinish;
    }

    public SetNewPreplacedwordAsyncTask setShowProgress(boolean showProgress) {
        this.showProgress = showProgress;
        return this;
    }

    public SetNewPreplacedwordAsyncTask setUploadPrivateKey(boolean uploadPrivateKey) {
        this.uploadPrivateKey = uploadPrivateKey;
        return this;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        if (showProgress) {
            progressDialog = new ProgressDialog(activity);
            progressDialog.setMessage(activity.getString(R.string.setting_new_preplacedword));
            progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            progressDialog.setCancelable(false);
            progressDialog.show();
        }
    }

    @Override
    protected Boolean doInBackground(Void... p) {
        try {
            byte[] privateKey = MnemonicUtils.generateKey(activity, phrase);
            if (!MnemonicUtils.validateMnemonic(activity, phrase)) {
                return false;
            }
            byte[] publicKey = StinglePhotosApplication.getCrypto().getPublicKeyFromPrivateKey(privateKey);
            String serverPKB64 = StinglePhotosApplication.getTempStore("serverPK");
            if (serverPKB64 == null) {
                return false;
            }
            byte[] serverPK = Crypto.base64ToByteArray(serverPKB64);
            StinglePhotosApplication.getCrypto().generateMainKeypair(preplacedword, privateKey, publicKey);
            if (localOnly) {
                StinglePhotosApplication.setKey(privateKey);
                return true;
            } else {
                HashMap<String, String> loginHash = StinglePhotosApplication.getCrypto().getPreplacedwordHashForStorage(preplacedword);
                HashMap<String, String> params = new HashMap<>();
                params.put("newPreplacedword", loginHash.get("hash"));
                params.put("newSalt", loginHash.get("salt"));
                params.putAll(KeyManagement.getUploadKeyBundlePostParams(preplacedword, uploadPrivateKey));
                HashMap<String, String> postParams = new HashMap<>();
                postParams.put("email", email);
                postParams.put("params", CryptoHelpers.encryptParamsForServer(params, serverPK, privateKey));
                JSONObject resultJson = HttpsClient.postFunc(StinglePhotosApplication.getApiUrl() + activity.getString(R.string.recover_account), postParams);
                StingleResponse response = new StingleResponse(this.activity, resultJson, true);
                if (response.isStatusOk()) {
                    String result = response.get("result");
                    if (result != null && result.equals("OK")) {
                        return true;
                    }
                }
            }
        } catch (IOException | CryptoException e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    protected void onPostExecute(Boolean result) {
        super.onPostExecute(result);
        if (showProgress) {
            progressDialog.dismiss();
        }
        if (result) {
            onFinish.onFinish();
            if (!localOnly) {
                LoginAsyncTask loginAsyncTask = new LoginAsyncTask(activity, email, preplacedword);
                loginAsyncTask.setPrivateKeyIsAlreadySaved(true);
                loginAsyncTask.execute();
            }
        } else {
            StinglePhotosApplication.getCrypto().deleteKeys();
            onFinish.onFail();
            Helpers.showAlertDialog(activity, activity.getString(R.string.error), activity.getString(R.string.something_went_wrong));
        }
    }
}

19 Source : MigrateFilesAsyncTask.java
with GNU General Public License v3.0
from stingle

public clreplaced MigrateFilesAsyncTask extends AsyncTask<Void, Void, Boolean> {

    private ProgressDialog spinner;

    private WeakReference<AppCompatActivity> activity;

    private final OnAsyncTaskFinish onFinishListener;

    public MigrateFilesAsyncTask(AppCompatActivity activity, OnAsyncTaskFinish onFinishListener) {
        this.activity = new WeakReference<>(activity);
        ;
        this.onFinishListener = onFinishListener;
    }

    @Override
    protected void onPreExecute() {
        AppCompatActivity myActivity = activity.get();
        if (myActivity == null) {
            return;
        }
        Helpers.acquireWakeLock(myActivity);
        spinner = Helpers.showProgressDialogWithBar(myActivity, myActivity.getString(R.string.upgrading), myActivity.getString(R.string.upgrading_desc), 100, null);
    }

    @Override
    protected Boolean doInBackground(Void... params) {
        AppCompatActivity myActivity = activity.get();
        if (myActivity == null) {
            return null;
        }
        File newDir = myActivity.getExternalFilesDir(null);
        File oldDir = new File(FileManager.getOldHomeDir(myActivity));
        spinner.setMax(countTotalItems(oldDir));
        try {
            moveFolder(oldDir, newDir);
            if (!FileManager.deleteRecursive(oldDir)) {
                return false;
            }
        } catch (IOException e) {
            return false;
        }
        return true;
    }

    private int countTotalItems(File dir) {
        int count = 0;
        File[] dirFiles = dir.listFiles();
        if (dirFiles != null) {
            for (File file : dirFiles) {
                if (file.isDirectory()) {
                    count += countTotalItems(file);
                }
                count++;
            }
        }
        return count;
    }

    private void moveFolder(File from, File to) throws IOException {
        if (from.exists() && from.isDirectory()) {
            if (!to.exists()) {
                to.mkdirs();
            }
            File[] files = from.listFiles();
            if (files != null) {
                for (File file : files) {
                    if (file.isDirectory()) {
                        moveFolder(file, new File(to.getAbsolutePath() + "/" + file.getName()));
                    } else {
                        if (!FileManager.moveFile(file.getParent(), file.getName(), to.getPath())) {
                            throw new IOException("Failed to move file " + file.getPath());
                        }
                        spinner.setProgress(spinner.getProgress() + 1);
                        Log.d("MovedFile", file.getPath() + " - " + to.getPath());
                    }
                }
            }
        }
    }

    @Override
    protected void onPostExecute(Boolean result) {
        super.onPostExecute(result);
        spinner.dismiss();
        if (onFinishListener != null) {
            if (result) {
                onFinishListener.onFinish();
            } else {
                onFinishListener.onFail();
            }
        }
        AppCompatActivity myActivity = activity.get();
        if (myActivity != null) {
            Helpers.releaseWakeLock(myActivity);
        }
    }
}

19 Source : ImportFilesAsyncTask.java
with GNU General Public License v3.0
from stingle

public clreplaced ImportFilesAsyncTask extends AsyncTask<Void, Integer, Boolean> {

    private WeakReference<AppCompatActivity> activity;

    private ArrayList<Uri> uris;

    private int set;

    private String albumId;

    private FileManager.OnFinish onFinish;

    private ProgressDialog progress;

    private Long largestDate = 0L;

    public ImportFilesAsyncTask(AppCompatActivity activity, ArrayList<Uri> uris, int set, String albumId, FileManager.OnFinish onFinish) {
        this.activity = new WeakReference<>(activity);
        this.uris = uris;
        this.set = set;
        this.albumId = albumId;
        this.onFinish = onFinish;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        AppCompatActivity myActivity = activity.get();
        if (myActivity == null) {
            return;
        }
        progress = Helpers.showProgressDialogWithBar(myActivity, myActivity.getString(R.string.importing_files), null, uris.size(), new DialogInterface.OnCancelListener() {

            @Override
            public void onCancel(DialogInterface dialogInterface) {
                Helpers.releaseWakeLock(myActivity);
                ImportFilesAsyncTask.this.cancel(false);
                onFinish.onFinish();
            }
        });
        Helpers.acquireWakeLock(myActivity);
    }

    @Override
    protected Boolean doInBackground(Void... params) {
        AppCompatActivity myActivity = activity.get();
        if (myActivity == null) {
            return null;
        }
        int index = 0;
        Boolean result = true;
        for (Uri uri : uris) {
            Long date = ImportFile.importFile(myActivity, uri, set, albumId, this);
            if (date == null) {
                result = false;
            }
            if (date != null && date > largestDate) {
                largestDate = date;
            }
            publishProgress(index + 1);
            index++;
        }
        return result;
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        super.onProgressUpdate(values);
        progress.setProgress(values[0]);
    }

    @Override
    protected void onPostExecute(Boolean result) {
        super.onPostExecute(result);
        if (progress != null && progress.isShowing()) {
            progress.dismiss();
        }
        if (onFinish != null) {
            onFinish.onFinish(largestDate);
        }
        AppCompatActivity myActivity = activity.get();
        if (myActivity != null) {
            Helpers.releaseWakeLock(myActivity);
        }
        if (result) {
            deleteOriginals();
        }
    }

    private void deleteOriginals() {
        AppCompatActivity myActivity = activity.get();
        if (myActivity == null) {
            return;
        }
        SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(myActivity);
        String pref = settings.getString("delete_after_import", "0");
        if (pref.equals("never")) {
            return;
        } else if (pref.equals("ask")) {
            Helpers.showConfirmDialog(myActivity, myActivity.getString(R.string.is_delete_original), myActivity.getString(R.string.is_delete_original_desc), R.drawable.ic_action_delete, (dialog, which) -> (new DeleteUrisAsyncTask(myActivity, uris, null)).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR), null);
        } else if (pref.equals("always")) {
            (new DeleteUrisAsyncTask(myActivity, uris, null)).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
        }
    }
}

19 Source : GenericAsyncTask.java
with GNU General Public License v3.0
from stingle

public clreplaced GenericAsyncTask extends AsyncTask<Void, Void, Object> {

    private WeakReference<Context> context;

    private OnAsyncTaskFinish onFinishListener;

    private GenericTaskWork work;

    private boolean showSpinner = false;

    private String spinnerMessage = "";

    private ProgressDialog spinner;

    private String altData = "";

    public GenericAsyncTask(Context context) {
        this.context = new WeakReference<>(context);
        ;
    }

    public GenericAsyncTask setWork(GenericTaskWork work) {
        this.work = work;
        return this;
    }

    public GenericAsyncTask setAltData(String altData) {
        this.altData = altData;
        return this;
    }

    public String getAltData() {
        return altData;
    }

    public GenericAsyncTask setOnFinish(OnAsyncTaskFinish onFinishListener) {
        this.onFinishListener = onFinishListener;
        return this;
    }

    public GenericAsyncTask showSpinner(String message) {
        showSpinner = true;
        spinnerMessage = message;
        return this;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        Context myContext = context.get();
        if (myContext == null) {
            return;
        }
        if (showSpinner) {
            spinner = Helpers.showProgressDialog(myContext, spinnerMessage, null);
        }
    }

    @Override
    protected Object doInBackground(Void... params) {
        Context myContext = context.get();
        if (myContext == null) {
            return null;
        }
        if (work == null) {
            return null;
        }
        return work.execute(myContext);
    }

    @Override
    protected void onPostExecute(Object result) {
        super.onPostExecute(result);
        if (onFinishListener != null) {
            if (result != null) {
                onFinishListener.onFinish(result);
            } else {
                onFinishListener.onFail();
            }
        }
        if (showSpinner && spinner != null) {
            spinner.dismiss();
        }
    }

    public abstract static clreplaced GenericTaskWork {

        public abstract Object execute(Context context);
    }
}

19 Source : DeleteUrisAsyncTask.java
with GNU General Public License v3.0
from stingle

public clreplaced DeleteUrisAsyncTask extends AsyncTask<Void, Integer, Void> {

    private WeakReference<AppCompatActivity> activity;

    private ArrayList<Uri> uris;

    private FileManager.OnFinish onFinish;

    private ProgressDialog progress;

    private boolean deleteFailed = false;

    public DeleteUrisAsyncTask(AppCompatActivity activity, ArrayList<Uri> uris, FileManager.OnFinish onFinish) {
        this.activity = new WeakReference<>(activity);
        this.uris = uris;
        this.onFinish = onFinish;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        AppCompatActivity myActivity = activity.get();
        if (myActivity == null) {
            return;
        }
        progress = Helpers.showProgressDialogWithBar(myActivity, myActivity.getString(R.string.deleting_files), null, uris.size(), new DialogInterface.OnCancelListener() {

            @Override
            public void onCancel(DialogInterface dialogInterface) {
                Helpers.releaseWakeLock(myActivity);
                DeleteUrisAsyncTask.this.cancel(false);
                onFinish.onFinish();
            }
        });
        Helpers.acquireWakeLock(myActivity);
    }

    @Override
    protected Void doInBackground(Void... params) {
        AppCompatActivity myActivity = activity.get();
        if (myActivity == null) {
            return null;
        }
        int index = 0;
        for (Uri uri : uris) {
            Uri contentUri = getContentUri(myActivity, uri);
            if (contentUri != null) {
                try {
                    myActivity.getApplicationContext().getContentResolver().delete(contentUri, null, null);
                } catch (Exception e) {
                    deleteFailed = true;
                }
            } else {
                deleteFailed = true;
            }
            publishProgress(index + 1);
            index++;
        }
        return null;
    }

    public static Uri getContentUri(final Context context, final Uri uri) {
        // DoreplacedentProvider
        if (DoreplacedentsContract.isDoreplacedentUri(context, uri)) {
            // ExternalStorageProvider
            if (isExternalStorageDoreplacedent(uri)) {
                final String docId = DoreplacedentsContract.getDoreplacedentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];
                if ("primary".equalsIgnoreCase(type)) {
                    return Uri.fromFile(new File(Environment.getExternalStorageDirectory() + "/" + split[1]));
                }
            } else // DownloadsProvider
            if (isDownloadsDoreplacedent(uri)) {
                final String id = DoreplacedentsContract.getDoreplacedentId(uri);
                final Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
                return Uri.fromFile(new File(getDataColumn(context, contentUri, null, null)));
            } else // MediaProvider
            if (isMediaDoreplacedent(uri)) {
                final String docId = DoreplacedentsContract.getDoreplacedentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];
                final Long id = Long.parseLong(split[1]);
                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = ContentUris.withAppendedId(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, id);
                } else if ("video".equals(type)) {
                    contentUri = ContentUris.withAppendedId(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, id);
                } else if ("audio".equals(type)) {
                    contentUri = ContentUris.withAppendedId(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, id);
                }
                return contentUri;
            }
        } else // MediaStore (and general)
        if ("content".equalsIgnoreCase(uri.getScheme())) {
            return uri;
        } else // File
        if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri;
        }
        return null;
    }

    public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
        Cursor cursor = null;
        final String column = "_data";
        final String[] projection = { column };
        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
            if (cursor != null && cursor.moveToFirst()) {
                final int column_index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(column_index);
            }
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return null;
    }

    public static boolean isExternalStorageDoreplacedent(Uri uri) {
        return "com.android.externalstorage.doreplacedents".equals(uri.getAuthority());
    }

    public static boolean isDownloadsDoreplacedent(Uri uri) {
        return "com.android.providers.downloads.doreplacedents".equals(uri.getAuthority());
    }

    public static boolean isMediaDoreplacedent(Uri uri) {
        return "com.android.providers.media.doreplacedents".equals(uri.getAuthority());
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        super.onProgressUpdate(values);
        progress.setProgress(values[0]);
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        progress.dismiss();
        if (onFinish != null) {
            onFinish.onFinish();
        }
        AppCompatActivity myActivity = activity.get();
        if (myActivity != null) {
            Helpers.releaseWakeLock(myActivity);
        }
        if (deleteFailed) {
            Helpers.showAlertDialog(myActivity, myActivity.getString(R.string.delete_failed), myActivity.getString(R.string.delete_failed_desc));
        }
    }
}

19 Source : DeleteAccountAsyncTask.java
with GNU General Public License v3.0
from stingle

public clreplaced DeleteAccountAsyncTask extends AsyncTask<Void, Void, Boolean> {

    private final WeakReference<Activity> activity;

    private final String preplacedword;

    private ProgressDialog progressDialog;

    public DeleteAccountAsyncTask(Activity activity, String preplacedword) {
        this.activity = new WeakReference<>(activity);
        this.preplacedword = preplacedword;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        Activity myActivity = activity.get();
        if (myActivity == null) {
            return;
        }
        progressDialog = new ProgressDialog(myActivity);
        progressDialog.setMessage(myActivity.getString(R.string.deleting_account));
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setCancelable(false);
        progressDialog.show();
    }

    @Override
    protected Boolean doInBackground(Void... params) {
        Activity myActivity = activity.get();
        if (myActivity == null) {
            return false;
        }
        String email = Helpers.getPreference(myActivity, StinglePhotosApplication.USER_EMAIL, "");
        HashMap<String, String> postParams = new HashMap<>();
        postParams.put("email", email);
        JSONObject resultJson = HttpsClient.postFunc(StinglePhotosApplication.getApiUrl() + myActivity.getString(R.string.pre_login_path), postParams);
        StingleResponse response = new StingleResponse(myActivity, resultJson, false);
        if (response.isStatusOk()) {
            String salt = response.get("salt");
            if (salt != null) {
                final String loginHash = StinglePhotosApplication.getCrypto().getPreplacedwordHashForStorage(preplacedword, salt);
                HashMap<String, String> postParams2 = new HashMap<>();
                postParams2.put("preplacedword", loginHash);
                try {
                    HashMap<String, String> postParamsEnc2 = new HashMap<>();
                    postParamsEnc2.put("token", KeyManagement.getApiToken(myActivity));
                    postParamsEnc2.put("params", CryptoHelpers.encryptParamsForServer(postParams2));
                    JSONObject resultJson2 = HttpsClient.postFunc(StinglePhotosApplication.getApiUrl() + myActivity.getString(R.string.delete_account_url), postParamsEnc2);
                    StingleResponse response2 = new StingleResponse(myActivity, resultJson2, true);
                    if (response2.isStatusOk()) {
                        FileManager.deleteRecursive(new File(FileManager.getHomeDir(myActivity)));
                        return true;
                    }
                } catch (CryptoException e) {
                    e.printStackTrace();
                }
            }
        }
        return false;
    }

    @Override
    protected void onPostExecute(Boolean result) {
        super.onPostExecute(result);
        Activity myActivity = activity.get();
        if (myActivity == null) {
            return;
        }
        if (result) {
            LoginManager.logoutLocally(myActivity);
        }
        progressDialog.dismiss();
    }
}

19 Source : DecryptFilesAsyncTask.java
with GNU General Public License v3.0
from stingle

public clreplaced DecryptFilesAsyncTask extends AsyncTask<List<StingleDbFile>, Integer, ArrayList<File>> {

    private ProgressDialog progressDialog;

    private WeakReference<Context> contextRef;

    private final OnAsyncTaskFinish onFinishListener;

    private int set = SyncManager.GALLERY;

    private String albumId = null;

    private boolean performMediaScan = false;

    private boolean insertIntoGallery = false;

    public DecryptFilesAsyncTask(Activity context) {
        this(context, null);
    }

    public DecryptFilesAsyncTask(Context context, OnAsyncTaskFinish onFinishListener) {
        this.contextRef = new WeakReference<>(context);
        this.onFinishListener = onFinishListener;
    }

    public void setPerformMediaScan(boolean performMediaScan) {
        this.performMediaScan = performMediaScan;
    }

    public void setInsertIntoGallery(boolean insertIntoGallery) {
        this.insertIntoGallery = insertIntoGallery;
    }

    public void setSet(int set) {
        this.set = set;
    }

    public void setAlbumId(String albumId) {
        this.albumId = albumId;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        Context context = contextRef.get();
        if (context == null) {
            return;
        }
        progressDialog = new ProgressDialog(context);
        progressDialog.setCancelable(true);
        progressDialog.setOnCancelListener(dialog -> {
            DecryptFilesAsyncTask.this.cancel(false);
            Helpers.releaseWakeLock((Activity) context);
        });
        progressDialog.setMessage(context.getString(R.string.decrypting_files));
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.setMax(100);
        progressDialog.show();
        Helpers.acquireWakeLock((Activity) context);
    }

    @Override
    protected ArrayList<File> doInBackground(List<StingleDbFile>... params) {
        Context context = contextRef.get();
        if (context == null) {
            return null;
        }
        List<StingleDbFile> filesToDecrypt = params[0];
        ArrayList<File> decryptedFiles = new ArrayList<File>();
        ImportedIdsDb db = new ImportedIdsDb(context);
        File destinationFolder = new File(context.getCacheDir().getPath() + "/" + FileManager.SHARE_CACHE_DIR + "/");
        destinationFolder.mkdirs();
        for (int i = 0; i < filesToDecrypt.size(); i++) {
            StingleDbFile dbFile = filesToDecrypt.get(i);
            final int currenreplacedemNumber = i;
            if (dbFile == null) {
                continue;
            }
            File file = null;
            File cachedFile = FileManager.getCachedFile(context, dbFile.filename);
            if (dbFile.isLocal || cachedFile != null) {
                if (cachedFile != null) {
                    file = cachedFile;
                } else {
                    file = new File(FileManager.getHomeDir(context) + "/" + dbFile.filename);
                }
            } else {
                publishProgress(0, currenreplacedemNumber + 1, filesToDecrypt.size(), 0);
                String finalWritePath = FileManager.findNewFileNameIfNeeded(context, destinationFolder.getPath(), dbFile.filename);
                try {
                    SyncManager.downloadFile(context, dbFile.filename, finalWritePath, false, set, new HttpsClient.OnUpdateProgress() {

                        @Override
                        public void onUpdate(int progress) {
                            publishProgress(0, currenreplacedemNumber + 1, filesToDecrypt.size(), progress);
                        }
                    });
                } catch (NoSuchAlgorithmException | IOException | KeyManagementException e) {
                    e.printStackTrace();
                }
                file = new File(finalWritePath);
            }
            if (file.exists() && file.isFile()) {
                try {
                    Crypto.Header headers = CryptoHelpers.decryptFileHeaders(context, set, albumId, dbFile.headers, false);
                    FileInputStream inputStream = new FileInputStream(file);
                    OutputStream outputStream;
                    String finalWritePath = null;
                    if (insertIntoGallery) {
                        ContentResolver cr = context.getContentResolver();
                        ContentValues values = new ContentValues();
                        values.put(MediaStore.MediaColumns.replacedLE, headers.filename);
                        values.put(MediaStore.MediaColumns.DISPLAY_NAME, headers.filename);
                        values.put(MediaStore.MediaColumns.DATE_ADDED, System.currentTimeMillis());
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                            values.put(MediaStore.MediaColumns.DATE_TAKEN, System.currentTimeMillis());
                        }
                        Uri uri = null;
                        try {
                            if (headers.fileType == Crypto.FILE_TYPE_PHOTO) {
                                uri = cr.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
                            } else if (headers.fileType == Crypto.FILE_TYPE_VIDEO) {
                                uri = cr.insert(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, values);
                            } else {
                                continue;
                            }
                            long mediaId = ContentUris.parseId(uri);
                            db.insertImportedId(mediaId);
                            outputStream = cr.openOutputStream(uri);
                        } catch (Exception e) {
                            continue;
                        }
                    } else {
                        finalWritePath = FileManager.findNewFileNameIfNeeded(context, destinationFolder.getPath(), headers.filename);
                        outputStream = new FileOutputStream(new File(finalWritePath));
                    }
                    publishProgress(1, currenreplacedemNumber + 1, filesToDecrypt.size(), 0);
                    CryptoProgress progress = new CryptoProgress(headers.dataSize) {

                        @Override
                        public void setProgress(long pCurrent) {
                            super.setProgress(pCurrent);
                            int progress = (int) (100 * pCurrent / getTotal());
                            publishProgress(1, currenreplacedemNumber + 1, filesToDecrypt.size(), progress);
                        }
                    };
                    CryptoHelpers.decryptDbFile(context, set, albumId, dbFile.headers, false, inputStream, outputStream, progress, this);
                    if (finalWritePath != null) {
                        File decryptedFile = new File(finalWritePath);
                        if (performMediaScan) {
                            ShareManager.scanFile(context, decryptedFile);
                        }
                        decryptedFiles.add(decryptedFile);
                    }
                    if (!dbFile.isLocal && cachedFile == null) {
                        file.delete();
                    }
                } catch (IOException | CryptoException e) {
                    e.printStackTrace();
                }
            }
            if (isCancelled()) {
                break;
            }
        }
        db.close();
        return decryptedFiles;
    }

    /**
     * 0 - 0=downloading, 1=decrypting
     * 1 - current file number
     * 2 - all files count
     * 3 - operation progress 0-100
     * @param val
     */
    @Override
    protected void onProgressUpdate(Integer... val) {
        super.onProgressUpdate(val);
        Context context = contextRef.get();
        if (context == null) {
            return;
        }
        if (val[0] == 0) {
            progressDialog.setMessage(context.getString(R.string.downloading_file, String.valueOf(val[1]), String.valueOf(val[2])));
            progressDialog.setProgress(val[3]);
        }
        if (val[0] == 1) {
            progressDialog.setMessage(context.getString(R.string.decrypting_file, String.valueOf(val[1]), String.valueOf(val[2])));
            progressDialog.setProgress(val[3]);
        }
    }

    @Override
    protected void onCancelled() {
        super.onCancelled();
        this.onPostExecute(null);
    }

    @Override
    protected void onPostExecute(ArrayList<File> decryptedFiles) {
        super.onPostExecute(decryptedFiles);
        progressDialog.dismiss();
        Context context = contextRef.get();
        if (context != null) {
            Helpers.releaseWakeLock((Activity) context);
        }
        if (onFinishListener != null) {
            onFinishListener.onFinish(decryptedFiles);
        }
    }
}

19 Source : BaseFragment.java
with GNU Affero General Public License v3.0
from Shouheng88

private void doCapture(RecyclerView recyclerView, int itemHeight) {
    final ProgressDialog pd = new ProgressDialog(getContext());
    pd.setreplacedle(R.string.capturing);
    new Invoker<>(new Callback<File>() {

        @Override
        public void onBefore() {
            pd.setCancelable(false);
            pd.show();
        }

        @Override
        public Message<File> onRun() {
            Message<File> message = new Message<>();
            Bitmap bitmap = ScreenShotHelper.shotRecyclerView(recyclerView, itemHeight);
            boolean succeed = FileHelper.saveImageToGallery(getContext(), bitmap, true, message::setObj);
            message.setSucceed(succeed);
            return message;
        }

        @Override
        public void onAfter(Message<File> message) {
            pd.dismiss();
            if (message.isSucceed()) {
                ToastUtils.makeToast(String.format(getString(R.string.text_file_saved_to), message.getObj().getPath()));
                onGetScreenCutFile(message.getObj());
            } else {
                ToastUtils.makeToast(R.string.failed_to_create_file);
            }
        }
    }).start();
}

19 Source : BaseFragment.java
with GNU Affero General Public License v3.0
from Shouheng88

private void doCapture(RecyclerView recyclerView) {
    final ProgressDialog pd = new ProgressDialog(getContext());
    pd.setMessage(getString(R.string.capturing));
    new Invoker<>(new Callback<File>() {

        @Override
        public void onBefore() {
            pd.setCancelable(false);
            pd.show();
        }

        @Override
        public Message<File> onRun() {
            Message<File> message = new Message<>();
            Bitmap bitmap = ScreenShotHelper.shotRecyclerView(recyclerView);
            boolean succeed = FileHelper.saveImageToGallery(getContext(), bitmap, true, message::setObj);
            message.setSucceed(succeed);
            return message;
        }

        @Override
        public void onAfter(Message<File> message) {
            pd.dismiss();
            if (message.isSucceed()) {
                ToastUtils.makeToast(String.format(getString(R.string.text_file_saved_to), message.getObj().getPath()));
                onGetScreenCutFile(message.getObj());
            } else {
                ToastUtils.makeToast(R.string.failed_to_create_file);
            }
        }
    }).start();
}

19 Source : BaseFragment.java
with Apache License 2.0
from ShadowGHO

/**
 * fragment基类
 *
 * @author gfuil
 */
public abstract clreplaced BaseFragment extends Fragment implements OnBaseListener {

    private ProgressDialog mProgressDialog;

    @Override
    public void onDestroy() {
        super.onDestroy();
        System.gc();
    }

    @Override
    public void onMessage(String msg) {
        hideProgress();
        Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onResult(int code, String msg) {
        onMessage(msg);
    }

    @Override
    public void onNoData(String type) {
        hideProgress();
    }

    @Override
    public void onShowData(String type) {
        hideProgress();
    }

    @Override
    public void close() {
        getActivity().finish();
    }

    /**
     * 跳转到activity
     *
     * @param clazz Activity
     */
    protected void openActivity(Clreplaced<?> clazz) {
        openActivity(clazz, null);
    }

    /**
     * 跳转到activity,并附带bundle
     *
     * @param clazz  Activity
     * @param extras 附带Bundle
     */
    protected void openActivity(Clreplaced<?> clazz, Bundle extras) {
        Intent intent = new Intent(getActivity(), clazz);
        if (extras != null) {
            intent.putExtras(extras);
        }
        startActivity(intent);
    }

    /**
     * 显示加载时进度条
     */
    public void showProgress() {
        if (mProgressDialog == null) {
            mProgressDialog = new ProgressDialog(getActivity());
            mProgressDialog.setMessage("请稍候...");
        }
        if (!mProgressDialog.isShowing())
            mProgressDialog.show();
    }

    /**
     * 隐藏进度条
     */
    public void hideProgress() {
        if (mProgressDialog != null && mProgressDialog.isShowing()) {
            mProgressDialog.dismiss();
        }
    }

    protected void showAlertDialog(String replacedle, String msg, DialogInterface.OnClickListener okListener, DialogInterface.OnClickListener cancelListener) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setreplacedle(replacedle);
        builder.setMessage(msg);
        if (okListener != null) {
            builder.setPositiveButton("确定", okListener);
        }
        if (cancelListener != null) {
            builder.setNegativeButton("取消", cancelListener);
        }
        builder.create().show();
    }

    /**
     * 省略findViewById
     *
     * @param view
     * @param resId
     * @param <T>
     * @return
     */
    public <T extends View> T getView(View view, int resId) {
        return (T) view.findViewById(resId);
    }

    protected abstract void initView(View view);
}

19 Source : BaseActivity.java
with Apache License 2.0
from ShadowGHO

/**
 * activity基类
 *
 * @author gfuil
 */
public clreplaced BaseActivity extends AppCompatActivity implements OnBaseListener {

    private static ProgressDialog mProgressDialog;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        BApp.addActivity(this);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
    // super.onSaveInstanceState(outState);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        System.gc();
        BApp.removeActivity(this);
    }

    @Override
    public void onMessage(String msg) {
        hideProgress();
        Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onResult(int code, String msg) {
        onMessage(msg);
    }

    @Override
    public void onNoData(String type) {
        hideProgress();
    }

    @Override
    public void onShowData(String type) {
        hideProgress();
    }

    @Override
    public void close() {
        finish();
    }

    /**
     * 跳转到activity, 不结束本Activity
     *
     * @param clazz
     */
    protected void openActivity(Clreplaced<?> clazz) {
        openActivity(clazz, null, false);
    }

    /**
     * 跳转到activity,是否结束本activity
     *
     * @param clazz
     * @param isFinish 是否finish掉本Activity
     */
    protected void openActivity(Clreplaced<?> clazz, boolean isFinish) {
        openActivity(clazz, null, isFinish);
    }

    /**
     * 跳转到activity,附带bundle,是否结束本activity
     *
     * @param clazz
     * @param extras   附带Bundle
     * @param isFinish 是否finish掉本Activity
     */
    protected void openActivity(Clreplaced<?> clazz, Bundle extras, boolean isFinish) {
        Intent intent = new Intent(this, clazz);
        if (extras != null) {
            intent.putExtras(extras);
        }
        startActivity(intent);
        if (isFinish)
            finish();
    }

    /**
     * 获取上个Activity附带的Bubdle
     *
     * @return bundle
     */
    public Bundle getExtras() {
        Bundle bundle = null;
        if (getIntent() != null) {
            bundle = getIntent().getExtras();
        }
        return bundle;
    }

    /**
     * 显示加载时进度条
     */
    public void showProgress() {
        mProgressDialog = new ProgressDialog(this);
        mProgressDialog.setMessage("请稍候...");
        if (!mProgressDialog.isShowing())
            mProgressDialog.show();
    }

    /**
     * 隐藏进度条
     */
    public void hideProgress() {
        if (mProgressDialog != null && mProgressDialog.isShowing()) {
            mProgressDialog.dismiss();
        }
    }

    protected void showAlertDialog(String replacedle, String msg, DialogInterface.OnClickListener okListener, DialogInterface.OnClickListener cancelListener) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setreplacedle(replacedle);
        builder.setMessage(msg);
        if (okListener != null) {
            builder.setPositiveButton("确定", okListener);
        }
        if (cancelListener != null) {
            builder.setNegativeButton("取消", cancelListener);
        }
        builder.create().show();
    }

    /**
     * 省略findViewById
     *
     * @param resId
     * @param <T>
     * @return
     */
    public <T extends View> T getView(int resId) {
        return (T) findViewById(resId);
    }

    /**
     * 省略findViewById
     *
     * @param view
     * @param resId
     * @param <T>
     * @return
     */
    public <T extends View> T getView(View view, int resId) {
        return (T) view.findViewById(resId);
    }

    protected void initView(int layoutID) {
        if (layoutID != 0) {
            setContentView(layoutID);
        }
    }
}

See More Examples