在asynctask结束时执行一个函数

时间:2017-02-18 18:09:41

标签: java android android-fragments android-asynctask android-toast

我现在有点问题: 在我调用的asynktask完成后,我试图在我的片段上创建可见的2个按钮。为此,我使用了这个:

while (!recordi.getterminé){

    } 
    terminé();

但这不是最佳的,我的应用程序没有响应:( 那么有什么解决方案可以在onPostExecute函数中调用函数terminé()吗? 感谢。

这是我的代码:

片段:

public class FragmentEnregistrer extends Fragment {

    String path,nomfinal, ip="http://MYIP/php";
    ImageButton mrecord,mupload,mlire;
    TextView Nomm;
    ProgressBar progressbar;
    int i=2;
    EnregistrerSon recordi;
    String id;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View myView= inflater.inflate(R.layout.enregistrer, container, false);

        mrecord= (ImageButton) myView.findViewById(record);
        mupload= (ImageButton) myView.findViewById(upload);
        mlire= (ImageButton) myView.findViewById(lire);
        Nomm = (TextView) myView.findViewById(NomWhizz);
        progressbar = (ProgressBar) myView.findViewById(progressBar);
        progressbar.setVisibility(View.INVISIBLE);

        id=((MainActivity)getActivity()).getIdentifiant();

        mrecord.setOnClickListener(new View.OnClickListener() {
            @RequiresApi(api = Build.VERSION_CODES.N)
            @Override
            public void onClick(View v) {
                Toast.makeText(getActivity().getApplicationContext(), "Enregistrement en cours", Toast.LENGTH_SHORT).show();
                String nomm = Nomm.getText().toString();
                nomm=nomm.replace(" ", "_");
                nomm=nomm.replace("&", "");

                final String finalNomm = nomm;
                recordi = new EnregistrerSon();
                recordi.execute(finalNomm);
                terminé();






            }
        });

        mupload.setOnClickListener(new View.OnClickListener() {
            @RequiresApi(api = Build.VERSION_CODES.N)
            @Override
            public void onClick(View v) {
                UploadOnServer upload = new UploadOnServer();
                progressbar.setVisibility(View.VISIBLE);
                upload.execute(path,nomfinal);
                progressbar.setVisibility(View.INVISIBLE);

                HttpGetRequest request = new HttpGetRequest();
                request.execute(ip+"/son/creation_son.php?nom_whiz="+nomfinal+"&id_createur="+id);

            }
        });

        mlire.setOnClickListener(new View.OnClickListener() {
            @RequiresApi(api = Build.VERSION_CODES.N)
            @Override
            public void onClick(View v) {
                LireSonLocal local = new LireSonLocal();
                Uri myUri = Uri.parse("file://"+recordi.getAccess());
                local.execute(myUri);

            }
        });

        return myView;
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    public void terminé(){
        Log.i("Enregistrement","terminé");
        Toast.makeText(getActivity().getApplicationContext(), "Enregistrement terminé", Toast.LENGTH_LONG).show();
        path = recordi.getAccess();
        nomfinal = recordi.getNomSansExtenssions();
        Log.i("nomfinale",nomfinal);
        mlire.setVisibility(View.VISIBLE);
        mupload.setVisibility(View.VISIBLE);
        Log.i("test","");
}

}

asynktask:

class EnregistrerSon extends AsyncTask<String,Void,String> {
    private Boolean isRecording = false;
    private Boolean termine = false;
    private String Nom, NOM;



    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    protected String doInBackground(String... params) {
        NOM = params[0];
        if(!isRecording){
            //configuration
            Looper.prepare();
            MediaRecorder mr = new MediaRecorder();
            mr.setAudioSource(MediaRecorder.AudioSource.DEFAULT);
            mr.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
            mr.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
            mr.setAudioChannels(1);
            mr.setAudioEncodingBitRate(1280000);
            mr.setAudioSamplingRate(9500000);
            mr.setOutputFile(getAccess());
            try {mr.prepare();}
            catch (IOException e) {e.printStackTrace();}

            //Demarage du record
            long start_time = System.currentTimeMillis(); //pendant 15 secondes
            long wait_time = 15000;
            long end_time = start_time + wait_time;
            mr.start();
            while (System.currentTimeMillis() < end_time){
                Long temps = end_time - System.currentTimeMillis();

                isRecording = true;
                //pendant 15 secondes
            }
            mr.stop();
            mr.reset();
            mr.release();
            isRecording = false;
            termine = true;
            //fin de l'enregistrement
        }
        return "lol";
    }


    @RequiresApi(api = Build.VERSION_CODES.N)
    protected void onPostExecute(String s) {
        super.onPostExecute(s);


    }

    @TargetApi(Build.VERSION_CODES.N)
    @RequiresApi(api = Build.VERSION_CODES.N)
    String getAccess(){
        MainActivity main = new MainActivity();
        if(Objects.equals(NOM, "Nom") || Objects.equals(NOM, "") || NOM == null ) {
            Calendar now = Calendar.getInstance();
            Nom = now.get(Calendar.HOUR_OF_DAY) + "_" + now.get(Calendar.DAY_OF_MONTH) + "_" + now.get(Calendar.MONTH) + "_" + now.get(Calendar.YEAR);
        }
        else{
            Nom = NOM;
        }
        File directory = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Whizz/");
        directory.mkdirs();
        String filename = directory +"/"+Nom+".mp3";
        Log.i("filename",filename);
        return filename;
    }

    Boolean getTerminé(){
        return termine;
    }

    String getNomSansExtenssions(){
        return Nom;
    }

}

3 个答案:

答案 0 :(得分:1)

首先,行while (!recordi.getterminé){} terminé();毫无意义,它等于:

while (!recordi.getterminé){

} 
terminé();

关于onPostExecute,是的,只需在其中编写函数调用:

protected void onPostExecute(String s) {

    // Anything here will be executed at the end, when doInBackground finishes
    terminé();
}

答案 1 :(得分:1)

terminé课程中执行方法AsyncTask。我建议有以下内容:

  1. FragmentEnregistrer课程中创建EnregistrerSon的实例字段。

    private FragmentEnregistrer fragmentEnregistrer;
    
  2. EnregistrerSon类中创建一个带有FragmentEnregistrer类预期参数的构造函数,并将该参数赋值给字段变量。

    public EnregistrerSon(FragmentEnregistrer fe) {
     this.fragmentEnregistrer = fe;
    }
    
  3. 然后,您可以在terminé方法中调用onPostExecute方法,如下所示:

    protected void onPostExecute(String s) {
      super.onPostExecute(s);
      this.fragmentEnregistrer.terminé();
    }
    
  4. 最后,在FragmentEnregistrer实例化上传递EnregistrerSon对象的实例。

    recordi = new EnregistrerSon(FragmentEnregistrer.this);
    recordi.execute(finalNomm);
    

答案 2 :(得分:1)

使用广播/接收器模式,onhandleintent()将在UI线程上运行,您可以在其中显示按钮。
1.启动异步任务。 2.定义BroadcastReceiver,在您的活动中实例化一个并相应地注册/取消注册。 3.在异步任务的onpostexecute()中调用sendBroadcast。在实例化AsyncTask时,您可能需要传递上下文参数。 应用程序广播接收器的onHandleIntent方法(在步骤2中实例化的方法)将在UI线程上运行,使所有这些UI更新安全。