Java 如何在创建文件期间显示进度条?

Java 如何在创建文件期间显示进度条?,java,android,progress,Java,Android,Progress,如何在创建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 pdfP

如何在创建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={"marco_marcoletto@hotmail.it"};
        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);

    }
}
public类TwoFragment扩展了android.support.v4.app.Fragment{
私人观点v;
意向选择器=null;
字符串myInt=“”;
字符串ciao=“”;
私有字符串=”;
私人ProgressBar pdfProgress;
进度任务;
公共双片段(){
//必需的空公共构造函数
}
@凌驾
创建时的公共void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
}
@凌驾
创建视图上的公共视图(布局、充气机、视图组容器、,
Bundle savedInstanceState){
//为该碎片膨胀布局
视图根视图=充气机。充气(R.layout.fragment\u-two,容器,false);
按钮mButton=(按钮)rootView.findviewbyd(R.id.newbutton);
mButton.setOnClickListener(新视图.OnClickListener(){
公共void onClick(视图v){
//sendmail();
//pdfProgress.setVisibility(View.GONE);
/*pdfProgress.setVisibility(View.VISIBLE);
createPDF();
pdfProgress.setVisibility(View.GONE);
viewPDF()*/
/*MyAsyncTask myTask=新建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.findviewbyd(R.id.ProgressBar);
pdfProgress.setVisibility(View.GONE);
//pdfProgress.setVisibility(视图.不可见);
//TextView titolo=(TextView)rootView.findViewById(R.id.quantitá3);
/*类MyAsyncTask扩展了AsyncTask{
@凌驾
受保护的Void doInBackground(Void…参数){
//这在新线程中运行!!!
//始终在另一个线程中运行长操作,这样GUI就永远不会被阻塞
createPDF();
返回null;
}
@凌驾
受保护的void onPostExecute(void v){
//这将在作业完成后在主线程中运行。
//您必须始终从主线程更新gui
pdfProgress.setVisibility(View.GONE);
viewPDF();
}
}
*/
Bundle bundle2=getArguments();
如果(bundle2!=null){
string=bundle2.getString(“scelta2”);
titolo3.setText(字符串);
}
/*Bundle bundle2=getArguments();
如果(bundle2!=null){
//myInt=bundle2.getString(“scelta2”,myInt);
cacca=bundle2.getString(“结果”,null);
//cacca=myInt;
//日志d(“再见”,cacca);
titolo3.setText(cacca);
}*/
//titolo3.setText(myInt);
/*Bundle bundle3=getArguments();
如果(bundle3!=null){
//字符串myInt3=bundle3.getString(“TotaleBire”,null);
//cazzo2=Integer.parseInt(myInt3);
int cazzo2=bundle3.getInt(“总息税”);
titolo2.setText(String.valueOf(cazzo2));
}
Bundle=getArguments();
if(bundle!=null){
//字符串myInt2=bundle2.getString(“totalepizze”,null);
//cazzo=Integer.parseInt(myInt2);
//titolo2.setText(myInt2);
String String=bundle.getString(“scelta3”,null);
titolo4.setText(字符串);
}
*/
返回rootView;
}
/*public void sendmail(){
意向意向=新意向(意向.行动\发送);
setData(Uri.parse(“mailto:”);
字符串[]到={“marco”_marcoletto@hotmail.it"};
intent.putExtra(intent.EXTRA_电子邮件,收件人);
意向。额外(意向。额外(主题“ciao”);
intent.putExtra(intent.EXTRA_TEXT,“zao”);
intent.setType(“message/rfc822”);
chooser=intent.createChooser(intent,“manda email”);
星触觉(选择器);
}*/
//@TargetApi(Build.VERSION\u CODES.M)
public void createPDF(){
单据单据=新单据();
试一试{
String path=Environment.getExternalStorageDirectory()
.getAbsolutePath()+“/droidText”;
文件目录=新文件(路径);
如果(!dir.exists())
dir.mkdirs();
Log.d(“PDFCreator”,“PDF路径:“+Path”);
//File File=新文件(dir,“sample.pdf”);
文件=新文件(dir,“salve.pdf”);
FileOutputStream fOut=新的FileOutputStream(文件);
getInstance(doc,fOut);
//打开文档
doc.open();
ByteArrayOutputStream=新建ByteArrayOutputStream();
位图位图=BitmapFactory.decodeResource(getContext())
.getResources(),R.drawable.androtuto);
压缩(bitmap.CompressFormat.JPEG,100,流);
Image myImg=Image.getInstance(stream.toByteArray());
myImg.setAlignment(图中);
//将图像添加到文档
新增文件(myImg);
段落p1=新段落(字符串);
Font paraFont=新字体(Font.COURIER);
p1.设置对准(段落对准中心);
p1.setFont(paraFont);
//在文件中添加段落
文件添加(p1);
p2段=新段(“安卓图图”);
Font paraFont2=新字体(Font.COURIER,14.0f,Color.GREEN);
p2.设置对齐(段落对齐中心);
p2.设置字体(paraFont2);
新增文件(p2);
stream=newbytearrayoutputstream();
位图=BitmapFactory.decodeResource(getContext())
private ProgressDialog processingDialog;
mButton.setOnClickListener(new View.OnClickListener() {
       public void onClick(View v) {
           processingDialog = ProgressDialog.show(this, "Creating PDF", "Please wait ...", true, false);
           createPDF();
           processingDialog.dismiss();
           viewPDF();
            }
        });  
private class MakePDF extends AsyncTask<Void, Void, Void> {

       private ProgressDialog processingDialog;
            Context cnt = null;

           MakePDF(Context cnt)
                 {
              this.cnt = cnt;
                  }

                @Override
                protected void onPreExecute() {
                    super.onPreExecute();

                    processingDialog = ProgressDialog.show( this.cnt, "Creating PDF", "Please wait ...", true, false);    

                }

                @Override
                protected Void doInBackground(Void... arg0) {
                          createPDF();                 
                         return null;
                }

                @Override
                protected void onPostExecute(Void aVoid) {
                    super.onPostExecute(aVoid);
                   processingDialog.dismiss();
                   viewPDF();
                    }
            }
new MakePDF(ActivityName.this).execute(); //here in constructor pass context of an calling activity.