开发者

onBackPressed and threads in android

I've got a thread running in my ListActivity and sometimes it takes too long to get the data from the internet, so maybe the user wants to quit and go back.

However, when I press the BACK button, it shows the previous view, but thread still remains in execution.

I override onBackPressed() method and set a breakfront but while debugging, I see that it doesn't go through it, so I don't know what else to do.

Any idea? Thank you!


Here is my code. Basically, I don't know why it doesn't execute onKeyPressed() even if it goes back to the previous activity when we press BACK bu开发者_开发问答tton.

code edit

// package + imports
public class ListaVideosActivity extends ListActivity implements Runnable {

    public static final String TAG_PL_ID = "id_playlist";
    public static final String TAG_PL_TITLE = "title_playlist";
    public static final String TAG_PL_HEADER = "header_playlist";
    protected int headerDrawable;
    private ProgressDialog pd;
    private Context mContext;
    private View header;
    private View footer;
    private Vibrator vibrator;
    private boolean firsTime = true;
    private Thread thread;
    private Long playlistId;
    private String playlistTitle;
    private Playlist pList;
    private SensorManager mSensorManager;
    private ShakeListener mShakeListener;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {

            switch (msg.what) {

                case 0:
                    Toast.makeText(mContext, R.string.noHostError,
                            Toast.LENGTH_LONG).show();
                case 1:

                    if (firsTime) {
                        // Shake
                        mShakeListener.setForceThreshHold(1.9);
                        mShakeListener
                                .setOnShakeListener(new ShakeListener.OnShakeListener() {
                                    @Override
                                    public void onShake() {

                                        if (pd == null || !pd.isShowing()) {
                                            vibrator.vibrate(300);
                                            updateVideosList();
                                        }

                                    }
                                });

                        MainTabActivity.tabHost.getTabWidget().setVisibility(
                                View.VISIBLE);

                        setContentView(R.layout.videos_list);

                        getListView().addHeaderView(header, null, false);
                        getListView().addFooterView(footer, null, false);

                        setListAdapter(new VideosListAdapter(mContext,
                                R.layout.videos_list_item, (ArrayList<Video>) pList
                                .getVideos()));

                        vibrator = ((Vibrator) getSystemService(Context.VIBRATOR_SERVICE));
                        firsTime = false;
                    } else {
                        ((VideosListAdapter) getListAdapter()).setItems((ArrayList<Video>) pList.getVideos());
                        ((VideosListAdapter) getListAdapter())
                                .notifyDataSetChanged();
                    }

                    if (pd != null)
                        pd.dismiss();
                    break;
            }
        }
    };

    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Context es el MainTabActivity
        mContext = getParent();
        MainTabActivity.tabHost.getTabWidget().setVisibility(View.GONE);

        playlistId = getIntent().getLongExtra(TAG_PL_ID, 0L);
        playlistTitle = getIntent().getStringExtra(TAG_PL_TITLE);
        headerDrawable = getIntent().getIntExtra(TAG_PL_HEADER, 0);

        setLoadingView();

        thread = new Thread(this);
        thread.start();

        createListHeader();

        mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
        mShakeListener = new ShakeListener(mSensorManager);
    }

    @Override
    protected void onPause() {
        mSensorManager.unregisterListener(mShakeListener);
        super.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mSensorManager.registerListener(mShakeListener, mSensorManager
                        .getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
                SensorManager.SENSOR_DELAY_GAME);
    }

    private void setLoadingView() {

        LayoutInflater inflater = (LayoutInflater) mContext
                .getSystemService(LAYOUT_INFLATER_SERVICE);
        View layout = inflater.inflate(R.layout.videos_loading_dialog, null);
        MainTabActivity.tabHost.getTabWidget().setVisibility(View.GONE);

        setContentView(layout);
    }

    private void createListHeader() {
        LayoutInflater inflater = (LayoutInflater) mContext
                .getSystemService(LAYOUT_INFLATER_SERVICE);
        header = inflater.inflate(R.layout.videos_list_header, null);
        footer = inflater.inflate(R.layout.screen_footer, null);

        ((ImageView) header).setImageResource(headerDrawable);
    }

    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {

        Video video = (Video) l.getItemAtPosition(position);
        Intent intent = new Intent(mContext, BCPlayerActivity.class);
        BCPlayerActivity.video = video;
        mContext.startActivity(intent);
    }

    public void run() {

        pList = BCVideoGetter.getPlaylistById(playlistId);
        if (pList != null) {
            // hay lista
            handler.sendEmptyMessage(1);
        } else {
            handler.sendEmptyMessage(0);
        }
    }

    @Override
    public void onBackPressed() {

        mSensorManager.unregisterListener(mShakeListener);
        thread.interrupt();
        PestanaProgramasTVActivity.group.back();
    }

    public boolean onCreateOptionsMenu(Menu menu) {

        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.news_list_menu, menu);

        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.update:

                updateVideosList();

                break;
            case R.id.settings:
                Intent settingsActivity = new Intent(mContext,
                        SettingsActivity.class);
                startActivity(settingsActivity);
                break;
        }
        return true;
    }

    private void updateVideosList() {

        if (pd == null || !pd.isShowing()) {
            pd = ProgressDialog.show(mContext, "", getResources().getString(
                    R.string.news_update), true);
            thread = new Thread(this);
            thread.start();
        }

    }
}


Any idea?

Stop the thread. Android does not deal with threads that you fork yourself. If you fork it, you stop it.

Exactly how to stop the thread depends on what the thread is doing, which you declined to explain here, so I can't give you concrete advice.


thread.stop() is a deprecated method. You can refer to this document to see how to properly kill a thread.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜