onBackPressed和android中的线程

我有一个线程运行在我的ListActivity ,有时需要很长时间才能从互联网获取数据,所以用户可能想退出并返回。

但是,当我按BACK按钮时,它显示前一个视图,但线程仍然保持执行状态。

我重写了onBackPressed()方法并设置了一个breakfront,但在调试时,我发现它没有经过它,所以我不知道还有什么要做。

任何想法? 谢谢!


这是我的代码。 基本上,我不知道为什么它不执行onKeyPressed()即使当我们按下BACK按钮时它会回到上一个活动。

代码编辑

// 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();
        }

    }
}

thread.stop()是不推荐使用的方法。 你可以参考这个文档来看看如何正确地杀死一个线程。


任何想法?

停止线程。 Android不处理你自己分叉的线程。 如果你分叉它,你停止它。

究竟如何阻止线程取决于线程在做什么,你拒绝在这里解释,所以我不能给你具体的建议。

链接地址: http://www.djcxy.com/p/32021.html

上一篇: onBackPressed and threads in android

下一篇: Android: NPE happens when getting picture from camera