Android:无法在runOnUiThread上为TextView设置文本

时间:2016-09-29 15:25:13

标签: android

在我的音乐播放器应用中,我有一个配置TextView和SeekBar的方法。在Runnable中,我检查Service实例中的onCompletion。这样,当一首歌完成后,可以重置TextView和SeekBar。在第一次打开活动时没关系。但是,当我销毁此活动时,我取消绑定Service实例,因此,当我启动新的Activity时,它连接到上一个Service,再次调用下面的方法。在这种情况下,无法重置TextView和SeekBar。通过制作两个Toast来检查它。它显示了我想要的新歌曲标题。但它不是在TextView和SeekBar上设置的。

  

这是我的活动

public class SongsPlayerActivity extends AppCompatActivity {
private ImageView
        iv_background;
private ImageView
        iv_start_and_pause, iv_next, iv_previous, iv_hate, iv_love;
private TextView
        tv_song_title;
private SeekBar sb_song_duration;

private Bundle bundle;
private String al_id,
        al_path,
        ar_path;
private Bitmap bitmap;
private ArrayList<Song> songs;
private Runnable getSongsInAlbum = new Runnable() {
    @Override
    public void run() {
        new AlbumImageLoader().execute(Variables.IP_ADDRESS +
                "/RESOURCES" +
                "/ALBUMS" +
                "/" + ar_path +
                "/" + al_path +
                "/image.png");

        try {
            new SongsLoader().execute(Variables.IP_ADDRESS +
                    "/Project_1_Web_Service" +
                    "/rest" +
                    "/Song" +
                    "/getSongsInAlbum" +
                    "/" + al_id).get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
};
private MusicService musicService;
private Intent intent;
private boolean musicBound = false;
public ServiceConnection musicConnection = new ServiceConnection() {
    @Override
    public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
        MusicService.MusicBinder musicBinder = (MusicService.MusicBinder) iBinder;
        musicService = musicBinder.getService();
        musicService.setAndPlay(ar_path, al_path, songs);

        setAndUpdateUI();

        musicBound = true;
        if(musicService.getSongPaused()){
            iv_start_and_pause.setImageResource(R.drawable.start);
        }
        else {
            iv_start_and_pause.setImageResource(R.drawable.pause);
        }
    }

    @Override
    public void onServiceDisconnected(ComponentName componentName) {
        musicBound = false;
    }
};

private Handler handler = new Handler();

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

    iv_background = (ImageView) findViewById(R.id.iv_background);
    iv_next = (ImageView) findViewById(R.id.iv_next);
    iv_previous = (ImageView) findViewById(R.id.iv_previous);
    iv_start_and_pause = (ImageView) findViewById(R.id.iv_start_and_pause);
    iv_hate = (ImageView) findViewById(R.id.iv_hate);
    iv_love = (ImageView) findViewById(R.id.iv_love);
    tv_song_title = (TextView) findViewById(R.id.tv_song_title);
    sb_song_duration = (SeekBar) findViewById(R.id.sb_song_duration);

    getAlbumInfo();

    loadSongsInAlbum();

    iv_next.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            playNextSong();
        }
    });

    iv_previous.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            playPreviousSong();
        }
    });

    iv_start_and_pause.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            startAndPauseSong();
        }
    });

    sb_song_duration.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            if(fromUser){
                musicService.seekTo(progress * 1000);
            }
        }
    });
}

@Override
protected void onStart() {
    super.onStart();
    if(intent == null){
        intent = new Intent(this, MusicService.class);
        startService(intent);
        bindService(intent,
                musicConnection,
                Context.BIND_AUTO_CREATE);
    }
}

@Override
protected void onDestroy(){
    unbindService(musicConnection);
    super.onDestroy();
}

public class AlbumImageLoader extends AsyncTask<String, Integer, String> {
    @Override
    protected String doInBackground(String... strings) {
        try {
            URL u = new URL(strings[0]);
            bitmap = BitmapFactory.decodeStream(u.openConnection().getInputStream());
            //bitmap = ImageHelper.blurBitmap(getBaseContext(), bitmap, 2f);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(String s) {
        iv_background.setImageBitmap(bitmap);
    }
}

public class SongsLoader extends AsyncTask<String, Integer, String>{

    @Override
    protected String doInBackground(String... strings) {
        FileReader fileReader = new FileReader();
        String s = fileReader.readFile(strings[0]);
        return s;
    }

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);
        try {
            JSONArray albumJSONArray = new JSONArray(s);
            for(int i = 0; i < albumJSONArray.length(); i++){
                JSONObject jsonObject = albumJSONArray.getJSONObject(i);
                songs.add(new Song(
                        jsonObject.getString("s_title"),
                        jsonObject.getString("ar_path"),
                        jsonObject.getString("al_path"),
                        jsonObject.getString("s_path")
                ));
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}

private void getAlbumInfo(){
    bundle = getIntent().getExtras();
    al_id = bundle.getString("al_id");
    al_path = bundle.getString("al_path");
    ar_path = bundle.getString("ar_path");
}

private void loadSongsInAlbum(){
    songs = new ArrayList<>();
    runOnUiThread(getSongsInAlbum);
}

private void playNextSong(){
    musicService.playNextSong();
    iv_start_and_pause.setImageResource(R.drawable.pause);

    setAndUpdateUI();
}

private void playPreviousSong(){
    musicService.playPreviousSong();
    iv_start_and_pause.setImageResource(R.drawable.pause);

    setAndUpdateUI();
}

private void startAndPauseSong(){
    if(musicService.getSongPaused()){
        musicService.startSong();
        musicService.setSongPaused(false);
        iv_start_and_pause.setImageResource(R.drawable.pause);
    }
    else {
        musicService.pauseSong();
        musicService.setSongPaused(true);
        iv_start_and_pause.setImageResource(R.drawable.start);
    }
}

private void setAndUpdateUI(){
    sb_song_duration.setMax(musicService.getSongDuration()/1000);
    tv_song_title.setText(musicService.getSongTitle());
    runOnUiThread(new Runnable() {
        @Override
        public void run() {
            sb_song_duration.setProgress(musicService.getCurrentPosition() / 1000);
            if(musicService.getSongCompleted()){
                sb_song_duration.setMax(musicService.getSongDuration() / 1000);
                tv_song_title.setText(musicService.getSongTitle());
                musicService.setSongCompleted(false);
            }
            handler.postDelayed(this, 1000);
        }
    });
}

1 个答案:

答案 0 :(得分:1)

尝试使用此方法

private Runnable updateUI = new Runnable() {
            @Override
            public void run() {

                sb_song_duration.setMax(musicService.getSongDuration() / 1000);
                tv_song_title.setText(musicService.getSongTitle());
                sb_song_duration.setProgress(musicService.getCurrentPosition() / 1000);

                if(musicService.getSongCompleted()){
                    musicService.setSongCompleted(false);
                }
                handler.postDelayed(this, 1000);
            }
        };


private void setAndUpdateUI(){
    runOnUiThread(updateUI);
}