[英]I'm using a Thread and when i left the Fragment, the app closes
我在片段中使用一个线程来更新在TextView中显示的时间。 但是,当我更改片段时,我的应用程序将关闭。 我相信在我离开该片段后,该线程将继续运行。 我试图在方法onPause()
和onDestroy()
使用Thread.interrupt()
,但我无法解决。
fragmentTime.java(没有Thread.interrupt()
)
public class EventosFragment extends Fragment {
TextView currentTime;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_eventos, container, false);
currentTime = (TextView) v.findViewById(R.id.currentTime);
Thread timer = new Thread() {
@Override
public void run() {
try {
while (!isInterrupted()) {
Thread.sleep(1000);
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
updateTime();
}
});
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
timer.start();
return v;
}
public void updateTime() {
Calendar c = Calendar.getInstance();
int hours = c.get(Calendar.HOUR_OF_DAY);
int minutes = c.get(Calendar.MINUTE);
int seconds = c.get(Calendar.SECOND);
SimpleDateFormat sourceFormat = new SimpleDateFormat("HH:mm:ss");
sourceFormat.setTimeZone(TimeZone.getDefault());
Date parsed = null; // => Date is in UTC now
try {
parsed = sourceFormat.parse(hours+":"+minutes+":"+seconds);
} catch (ParseException e) {
e.printStackTrace();
}
currentTime.setText(sourceFormat.format(parsed));
}
}
fragmentTime.java(带有Thread.interrupt()
)
public class EventosFragment extends Fragment {
TextView currentTime;
Thread timer;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_eventos, container, false);
currentTime = (TextView) v.findViewById(R.id.currentTime);
timer = new Thread() {
@Override
public void run() {
try {
while (!isInterrupted()) {
Thread.sleep(1000);
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
updateTime();
}
});
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
timer.start();
return v;
}
@Override
public void onDestroy() {
timer.interrupt();
super.onDestroy();
}
@Override
public void onResume() {
timer.start();
super.onResume();
}
@Override
public void onPause() {
timer.interrupt();
super.onPause();
}
public void updateTime() {
Calendar c = Calendar.getInstance();
int hours = c.get(Calendar.HOUR_OF_DAY);
int minutes = c.get(Calendar.MINUTE);
int seconds = c.get(Calendar.SECOND);
SimpleDateFormat sourceFormat = new SimpleDateFormat("HH:mm:ss");
sourceFormat.setTimeZone(TimeZone.getDefault());
Date parsed = null; // => Date is in UTC now
try {
parsed = sourceFormat.parse(hours+":"+minutes+":"+seconds);
} catch (ParseException e) {
e.printStackTrace();
}
currentTime.setText(sourceFormat.format(parsed));
}
}
getActivity
返回null
因为Fragment不再附加到Activity。
您可以通过在Fragment.onDetach
停止计时器来解决此问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.