0

我有两个按钮。第一个启动媒体播放器,第二个取消它:媒体播放器在AsyncTask并且我使用(线程-while)重复它我需要媒体播放器播放,直到用户在我启动它时按下取消它正在运行并且当我按下取消它停止(当我不出去页面布局时,)

private DoSomething doSomething;
    @Override   
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.first);
final MediaPlayer mp;
mp=MediaPlayer.create(this,R.raw.ab);

//===================================================
    final Button first=(Button)findViewById(R.id.button1);
    final Button second=(Button)findViewById(R.id.button2);
    first.setOnClickListener(new OnClickListener() {

        public void onClick(View arg0) { 
            //start your asynctask
           if(doSomething == null || doSomething.isCancelled()){
            doSomething = new DoSomething();
                doSomething = (DoSomething) doSomething.execute();
           }  }
    });

    second.setOnClickListener(new OnClickListener() {

        public void onClick(View arg0) {
   doSomething.cancel(true);

        }  });}

问题:当我退出布局并返回以取消异步任务时,出现问题

doSomething.cancel(true);

因为空指针doSomething看到asyntask在运行时没有运行

我用Status g=doSomething.getStatus(); 的是 PENDING not RUNNING

class DoSomething extends AsyncTask<Void, Void, Void>{

    @Override
    protected Void doInBackground(Void... params) {

        while(true){
            if(isCancelled()){
                break;
            }
            final MediaPlayer mp;
            mp=MediaPlayer.create(getBaseContext(),R.raw.ab);


                        mp.start();
                        mp.setOnCompletionListener(new OnCompletionListener() {

                            public void onCompletion(MediaPlayer mp) {
                                mp.release();
                            }
                        });

                try {
                    Thread.sleep(8 * 1000);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace()  }}
        return null;
    }}  
4

1 回答 1

0

解决问题的简单方法是将第二次点击更改为

second.setOnClickListener(new OnClickListener() {

        public void onClick(View arg0) {
          if(doSomething != null && !doSomething.isCancelled()){
              doSomething.cancel(true);
        }  
    })
;
于 2013-04-23T15:20:52.110 回答