我有一个应用程序,它从片段内部每1秒运行一个postDelayed任务,使用一个使用复选框启用/禁用的处理程序。 (工作正常)
当应用程序暂停时,runnable仍然会在后台生效,因为我想要它。但是,如果我恢复应用程序,我希望能够在使用handler.removeCallbacks(runnable)使checkBox变为unChecked时停止处理程序但是我得到一个NullPointerException。
有办法做到这一点吗?
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(checkBox1.isChecked()) {
if(deviceStart()==0) {
//Failed to start service
checkBox1.setChecked(false);
Toast.makeText(getActivity(), "Failed to Start Service. Please Try Again...",Toast.LENGTH_SHORT).show();
} else {
handler = new Handler();
handler.postDelayed(runnable, 1000);
}
} else {
if(pocketHaloStop()==0) {
//Failed to stop service
checkBox1.setChecked(true);
Toast.makeText(getActivity(), "Failed to Stop Service. Please Try Again...",Toast.LENGTH_SHORT).show();
} else {
handler.removeCallbacks(runnable); //This generates Null Pointer Exception if app is Resumed!
}
}
});

以下是Runnable和onPause / onResume:
的代码
private Runnable runnable = new Runnable() {
@Override
public void run() {
/* do what you need to do */
handler.postDelayed(this, 1000);
}
};
private void save(final boolean isChecked) {
mContext = getActivity();
SharedPreferences settings = mContext.getSharedPreferences("settings", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("Check", isChecked);
editor.commit();
}
private boolean load() {
mContext = getActivity();
SharedPreferences settings = mContext.getSharedPreferences("settings", Context.MODE_PRIVATE);
return settings.getBoolean("Check", false);
}
@Override
public void onResume() {
super.onResume();
checkBox1 = (CheckBox)view.findViewById(R.id.checkEnable);
checkBox1.setChecked(load());
}
@Override
public void onPause() {
super.onPause();
save(checkBox1.isChecked());
checkBox1.setOnClickListener(null);
}

答案 0 :(得分:1)
将Handler的创建移动到onCreate()。
....
public void onCreate(Bundle savedInstanceState) {
...
handler = new Handler();
...
}