在我的应用程序中,我想在CountDownTimer中使用一个线程,为此我写下面的代码。
但是几秒钟后运行应用程序会在LogCat中显示错误。
我的代码:
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_auction_detail_bid, null);
new CountDownTimer(newCalculateTime, 1000) {
public void onTick(long millisUntilFinished) {
if (millisUntilFinished / 1000 <= newCanOfferBeforeTime) {
Constants.currentActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
getlast6BidData();
}
});
}
}
public void onFinish() {
}
}.start();
return v;
}
private void getlast6BidData() {
thread = new Thread() {
@Override
public void run() {
getUpdateBidsList(Constants.detailAuctionGmodel.getRes().getDetail().getCalculate_end());
try {
sleep(last6RunStartTimer);
getlast6BidData();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
thread.start();
}
LogCat错误:
E/UncaughtException: java.lang.IllegalThreadStateException
at java.lang.Thread.start(Thread.java:722)
at com.app.android.Fragments.AuctionDetailBidFragment.getlast6BidData(AuctionDetailBidFragment.java:744)
at com.app.android.Fragments.AuctionDetailBidFragment.access$100(AuctionDetailBidFragment.java:73)
at com.app.android.Fragments.AuctionDetailBidFragment$12.run(AuctionDetailBidFragment.java:737)
我该如何解决?
答案 0 :(得分:1)
尝试使用Thread.isAlive()
方法检查线程是否存活。
private void getlast6BidData() {
thread = new Thread() {
@Override
public void run() {
getUpdateBidsList(Constants.detailAuctionGmodel.getRes().getDetail().getCalculate_end());
try {
sleep(last6RunStartTimer);
getlast6BidData();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
if (!thread.isAlive()){
thread.start();
}
}
修改强>
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
getlast6BidData();
}
});