如何在创建文件的过程中显示进度条?

2024-01-09

如何在创建 PDF 文件时单击按钮时显示进度条,并在创建文件完成后隐藏进度条?

  public class TwoFragment extends android.support.v4.app.Fragment {

    private View v;
    Intent chooser=null;
    String myInt="";
    String ciao="";
    private String string="";
    private ProgressBar pdfProgress;
    ProgressTask task;



    public TwoFragment() {
        // Required empty public constructor
    }


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

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment

        View rootView = inflater.inflate(R.layout.fragment_two, container, false);


        Button mButton = (Button) rootView.findViewById(R.id.newbutton);
        mButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {

                //sendemail();
               // pdfProgress.setVisibility(View.GONE);

               /* pdfProgress.setVisibility(View.VISIBLE);
                createPDF();
                pdfProgress.setVisibility(View.GONE);
                viewPDF();*/
                /*MyAsyncTask myTask = new MyAsyncTask();
                myTask.execute();
*/
                showProgress();



            }
        });
        TextView titolo3 = (TextView)rootView.findViewById(R.id.result);
        TextView titolo2 = (TextView)rootView.findViewById(R.id.result2);
        TextView titolo4 = (TextView)rootView.findViewById(R.id.resultpizze);
        pdfProgress = (ProgressBar)rootView.findViewById(R.id.progressbar);
        pdfProgress.setVisibility(View.GONE);

        //pdfProgress.setVisibility(View.INVISIBLE);


        //TextView titolo = (TextView)rootView.findViewById(R.id.quantità3);
     /*  class MyAsyncTask extends AsyncTask<Void, Void, Void> {
            @Override
            protected Void doInBackground(Void... params) {
                // This runs in new thread!!!
                // Always run long operations in another thread, so GUI will never be blocked
                createPDF();

                return null;
            }

            @Override
            protected void onPostExecute(Void v) {
                // This runs in MAIN thread, after the job's done.
                // You always have to update gui from main thread
                pdfProgress.setVisibility(View.GONE);
                viewPDF();
            }
        }
*/
  Bundle bundle2=getArguments();
        if(bundle2 != null){
             string = bundle2.getString("scelta2");
            titolo3.setText(string);

        }

    /*    Bundle bundle2=getArguments();
        if(bundle2 != null){
           //  myInt = bundle2.getString("scelta2",myInt);
            cacca=bundle2.getString("result",null);

            //cacca=myInt;
           // Log.d("ciao",cacca);
           titolo3.setText(cacca);
        }*/

        //titolo3.setText(myInt);


    /*    Bundle bundle3=getArguments();
        if(bundle3 != null){
           // String myInt3 = bundle3.getString("totalebirre", null);
           //  cazzo2=Integer.parseInt(myInt3);
           int cazzo2=bundle3.getInt("totalebirre");
            titolo2.setText(String.valueOf(cazzo2));



        }
        Bundle bundle=getArguments();
        if(bundle != null){
            // String myInt2 = bundle2.getString("totalepizze", null);
            //   cazzo=Integer.parseInt(myInt2);
            //titolo2.setText(myInt2);
            String string=bundle.getString("scelta3", null);
             titolo4.setText(string);

        }
*/


        return rootView;
    }


/* public void sendemail(){

        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.setData(Uri.parse("mailto:"));
        String[] to={"[email protected] /cdn-cgi/l/email-protection"};
        intent.putExtra(Intent.EXTRA_EMAIL,to);
        intent.putExtra(Intent.EXTRA_SUBJECT, "ciao");
        intent.putExtra(Intent.EXTRA_TEXT, "zao");
        intent.setType("message/rfc822");
        chooser=intent.createChooser(intent,"manda email");
        startActivity(chooser);
    }*/

   //@TargetApi(Build.VERSION_CODES.M)
    public void createPDF() {

       Document doc = new Document();

       try {
           String path = Environment.getExternalStorageDirectory()
                   .getAbsolutePath() + "/droidText";

           File dir = new File(path);
           if (!dir.exists())
               dir.mkdirs();

           Log.d("PDFCreator", "PDF Path: " + path);

           //File file = new File(dir, "sample.pdf");
           File file = new File(dir, "salve.pdf");

           FileOutputStream fOut = new FileOutputStream(file);

           PdfWriter.getInstance(doc, fOut);

           // open the document
           doc.open();
           ByteArrayOutputStream stream = new ByteArrayOutputStream();
           Bitmap bitmap = BitmapFactory.decodeResource(getContext()
                   .getResources(), R.drawable.androtuto);
           bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
           Image myImg = Image.getInstance(stream.toByteArray());
           myImg.setAlignment(Image.MIDDLE);

           // add image to document
           doc.add(myImg);
           Paragraph p1 = new Paragraph(string);
           Font paraFont = new Font(Font.COURIER);
           p1.setAlignment(Paragraph.ALIGN_CENTER);
           p1.setFont(paraFont);




           // add paragraph to document
           doc.add(p1);

           Paragraph p2 = new Paragraph("Bonjour Android Tuto");

           Font paraFont2 = new Font(Font.COURIER, 14.0f, Color.GREEN);
           p2.setAlignment(Paragraph.ALIGN_CENTER);
           p2.setFont(paraFont2);

           doc.add(p2);


           stream = new ByteArrayOutputStream();
           bitmap = BitmapFactory.decodeResource(getContext()
                   .getResources(), R.drawable.android);
           bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
           myImg = Image.getInstance(stream.toByteArray());
           myImg.setAlignment(Image.MIDDLE);

           // add image to document
           doc.add(myImg);

           // set footer
           Phrase footerText = new Phrase("Pied de page ");
           HeaderFooter pdfFooter = new HeaderFooter(footerText, false);
           doc.setFooter(pdfFooter);

       } catch (DocumentException de) {
          // Log.e("PDFCreator", "DocumentException:" + de);
           Log.e("PDFCreator", "DocumentException:" + de.getMessage());
       } catch (IOException e) {
         //  Log.e("PDFCreator", "ioException:" + e);
           Log.e("PDFCreator", "DocumentException:" + e.getMessage());


       } finally {
           doc.close();
       }

   }
    public void viewPDF(){
        String path = "/sdcard/droidText/salve.pdf";

        File targetFile = new File(path);
        Uri targetUri = Uri.fromFile(targetFile);

        Intent intent;
        intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(targetUri, "application/pdf");

        startActivity(intent);
    }
    private class ProgressTask extends AsyncTask<Integer,Integer,Void> {

        protected void onPreExecute() {
            pdfProgress.setMax(100); // set maximum progress to 100.
        }

        protected void onCancelled() {
            pdfProgress.setMax(0); // stop the progress
        }
        protected Void doInBackground(Integer... params) {
            int start=params[0];
            for(int i=start;i<=100;i+=5){
                try {
                    boolean cancelled=isCancelled();
                    if(!cancelled) {
                        publishProgress(i);
                        Log.v("Progress","increment " + i);
                        //onProgressUpdate(i);
                        SystemClock.sleep(1000);
                    }
                    createPDF();
                } catch (Exception e) {
                    Log.e("Error", e.toString());
                }
            }
            return null;
        }
        protected void onProgressUpdate(Integer... values) {

            // increment progress bar by progress value
            //setProgress(10);
        }
        protected void onPostExecute(Void result) {
            // async task finished
            Log.v("Progress", "Finished");
            viewPDF();
        }

    }
    public void showProgress() {
        task = new ProgressTask();
        // start progress bar with initial progress 10
        ///////////////////task.execute(10,10,null);
        task.execute(10);

    }
}

定义一个ProgressDialog在您的片段中,如下所示。下面的代码将添加一个ProgessDialog;要更新它以显示进度条,请阅读this http://www.tutorialspoint.com/android/android_progressbar.htm.

private ProgressDialog processingDialog;

现在,在你的onClick()

mButton.setOnClickListener(new View.OnClickListener() {
       public void onClick(View v) {
           processingDialog = ProgressDialog.show(this, "Creating PDF", "Please wait ...", true, false);
           createPDF();
           processingDialog.dismiss();
           viewPDF();
            }
        });  

这应该可以完成任务,但是,我还有一些建议给您。由于创建 PDF(我认为)会非常耗时,因此在 UI 线程上执行此操作可能不是一个好主意。相反,使用AsyncTask生成您的 PDFdoInBackground(),显示ProgressDialog,最后dismiss() it in onPostExecute().

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在创建文件的过程中显示进度条? 的相关文章

  • CookieManager.getInstance().removeAllCookie();不删除所有cookie

    我在应用程序的 onCreate 中调用 CookieManager getInstance removeAllCookie 我遇到了一个奇怪的问题 我看到 GET 请求中传递了意外的 cookie 值 事实上 cookie 值是一个非常非
  • Clip 在 Java 中播放 WAV 文件时出现严重延迟

    我编写了一段代码来读取 WAV 文件 大小约为 80 mb 并播放该文件 问题是声音播放效果很差 极度滞后 你能告诉我有什么问题吗 这是我的代码 我称之为doPlayJframe 构造函数内的函数 private void doPlay f
  • 在具有相同属性名称的不同数据类型上使用 ModelMapper

    我有两节课说Animal AnimalDto我想用ModelMapper将 Entity 转换为 DTO 反之亦然 但是对于具有相似名称的一些属性 这些类应该具有不同的数据类型 我该如何实现这一目标 动物 java public class
  • 反思 Groovy 脚本中声明的函数

    有没有一种方法可以获取 Groovy 脚本中声明的函数的反射数据 该脚本已通过GroovyShell目的 具体来说 我想枚举脚本中的函数并访问附加到它们的注释 Put this到 Groovy 脚本的最后一行 它将作为脚本的返回值 a la
  • Android构建apk:控制MANIFEST.MF

    Android 构建 APK 假设一个 apk 包含一个库 jar 例如 foo jar 该库具有 META INF MANIFEST MF 这对于它的运行很重要 但在APK中有一个包含签名数据的MANIFEST MF 并且lib jar
  • Android Webview 图像未加载

    我制作了一个简单的应用程序WebView 但有些图片无法加载 正确 在我的电脑上 错误 在模拟器中 Correct 错误 没有横幅 于是我用Chrome debug进行调试 发现我的代码被改变了 我不添加像noscript or style
  • 材质设计图标颜色

    应该是哪种颜色 暗 材质图标 在官方文档上 https www google com design spec style icons html icons system icons https www google com design s
  • 检查 protobuf 消息 - 如何按名称获取字段值?

    我似乎无法找到一种方法来验证 protobuf 消息中字段的值 而无需显式调用其 getter 我看到周围的例子使用Descriptors FieldDescriptor实例到达消息映射内部 但它们要么基于迭代器 要么由字段号驱动 一旦我有
  • 调节麦克风录音音量

    我们正在尝试调整录音时的音量级别 麦克风似乎非常敏感 会接收到很多静电 我们查看了 setVolumeControlStream 但找不到传入其中来控制麦克风的流 将您的音频源设置为 MIC using MediaRecorder Audi
  • 将 Long 转换为 DateTime 从 C# 日期到 Java 日期

    我一直尝试用Java读取二进制文件 而二进制文件是用C 编写的 其中一些数据包含日期时间数据 当 DateTime 数据写入文件 以二进制形式 时 它使用DateTime ToBinary on C 为了读取 DateTime 数据 它将首
  • 使用 AWS Java SDK 为现有 S3 对象设置 Expires 标头

    我正在更新 Amazon S3 存储桶中的现有对象以设置一些元数据 我想设置 HTTPExpires每个对象的标头以更好地处理 HTTP 1 0 客户端 我们正在使用AWS Java SDK http aws amazon com sdkf
  • 使用 SAX 进行 XML 解析 |如何处理特殊字符?

    我们有一个 JAVA 应用程序 可以从 SAP 系统中提取数据 解析数据并呈现给用户 使用 SAP JCo 连接器提取数据 最近我们抛出了一个异常 org xml sax SAXParseException 字符引用 是无效的 XML 字符
  • 当手机旋转(方向改变)时如何最好地重新创建标记/折线

    背景 开发一个使用 Android Google Map v2 的本机 Android 应用程序 使用android support v4 app FragmentActivity 在 Android v2 2 上运行 客观的 在更改手机方
  • Android中webview的截图方法

    我在 webview 中的 html5 canvas 上画了一些线 并尝试使用下面的代码截取 webview 的屏幕截图 WebView webView WebView findViewById R id webview webView s
  • Android JNI C 简单追加函数

    我想制作一个简单的函数 返回两个字符串的值 基本上 java public native String getAppendedString String name c jstring Java com example hellojni He
  • Java - 不要用 bufferedwriter 覆盖

    我有一个程序可以将人员添加到数组列表中 我想做的是将这些人也添加到文本文件中 但程序会覆盖第一行 因此这些人会被删除 如何告诉编译器在下一个空闲行写入 import java io import java util import javax
  • 休眠以持久保存日期

    有没有办法告诉 Hibernate java util Date 应该持久保存 我需要这个来解决 MySQL 中缺少的毫秒分辨率问题 您能想到这种方法有什么缺点吗 您可以自己创建字段long 或者使用自定义的UserType 实施后User
  • 如何修复“sessionFactory”或“hibernateTemplate”是必需的问题

    我正在使用 Spring Boot JPA WEB 和 MYSQL 创建我的 Web 应用程序 它总是说 sessionFactory or hibernateTemplate是必需的 我该如何修复它 我已经尝试过的东西 删除了本地 Mav
  • JAVA - 如何从扫描仪读取文件中检测到“\n”字符

    第一次海报 我在读取文本文件的扫描仪中读取返回字符时遇到问题 正在读取的文本文件如下所示 test txt start 2 0 30 30 1 1 90 30 0 test txt end 第一行 2 表示两个点 第二行 位置索引 0 xp
  • 在 Google 地图上绘制线条/路径

    我很长一段时间都在忙于寻找如何在 HelloMapView 中的地图上的两个 GPS 点之间画一条线 但没有运气 谁能告诉我该怎么做 假设我使用扩展 MapView 的 HelloMapView 我需要使用叠加层吗 如果是这样 我是否必须重

随机推荐