Android线程操作类(暂停、重新开启、停止)

场景:
在程序中如果需要在后台长时间做一件事情,比如联网获取数据等操作,就要用到线程。
但为了提高用户体验,有以下几点需要注意:
1、程序可见时线程开始运行;
2、程序不可见时线程暂停;
3、程序退出时停止线程;

以下根据我自己的程序提出一个公用的代码,大家可以把自己的业务逻辑套进去:


public class NetUtil2 extends Thread {

	//NewsBrief为新闻实体类;
	private List<NewsBrief> loopList = new ArrayList<NewsBrief>();
	
	private boolean isClose = false;
	
	//IObtainData为一个接口,因为很多程序在用,因此拿Map存储;
	private Map<Integer, IObtainData> obtainMap = new HashMap<Integer, IObtainData>();
	private int currentPage = 0;
	private boolean isPause = false;

	private NetUtil2() {
	}

	private static NetUtil2 single = null;

	public synchronized static NetUtil2 getInstance() {
		if (single == null) {
			single = new NetUtil2();
		}
		return single;
	}

	public synchronized void addNewsBrief(NewsBrief newsBrief) {
		loopList.add(newsBrief);
		//有数据要处理时唤醒线程
		this.notify();
	}

	public void setObtainDataListener(int channelId, IObtainData iod) {
		//添加回调
		if (!obtainMap.containsKey(channelId)) {
			obtainMap.put(channelId, iod);
		}
	}

	public void setCurrentPage(int page) {
		currentPage = page;
	}

	/**
	 * 暂停线程
	 */
	public synchronized void onThreadPause() {
		isPause = true;
	}

	/**
	 * 线程等待,不提供给外部调用
	 */
	private void onThreadWait() {
		try {
			synchronized (this) {
				this.wait();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 线程继续运行
	 */
	public synchronized void onThreadResume() {
		isPause = false;
		this.notify();
	}

	/**
	 * 关闭线程
	 */
	public synchronized void closeThread() {
		try {
			notify();
			setClose(true);
			interrupt();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public boolean isClose() {
		return isClose;
	}

	public void setClose(boolean isClose) {
		this.isClose = isClose;
	}

	@Override
	public void run() {
		while (!isClose && !isInterrupted()) {
			if (loopList.size() > 0 && !isPause) {
				int index = 0;
				NewsBrief newsBrief = null;
				// 当前页面优先加载
				for (int i = 0; i < loopList.size(); i++) {
					if (loopList.get(i).getChannelId() == currentPage) {
						newsBrief = loopList.get(i);
						index = i;
						break;
					}
				}
				if (null == newsBrief) {
					newsBrief = loopList.get(0);
				}
				String reslut = getNewsContent(newsBrief);

				if (!"-1".equals(reslut)) {
					// 获取成功,更新
					if (obtainMap.containsKey(newsBrief.getChannelId())) {
						obtainMap.get(newsBrief.getChannelId())
								.updateNewsBrief(newsBrief);
					}
					synchronized (loopList) {
						loopList.remove(index);
					}
				} else {
					//获取失败,移至队尾
					synchronized (loopList) {
						NewsBrief nb = loopList.remove(index);
						loopList.add(nb);
					}
				}
				try {
					Thread.sleep(300);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			} else {
				onThreadWait();
			}
		}
	}
}


注意:
线程的暂停用isPause控制,说白了其实就是不让线程进入wait状态;

你可能感兴趣的:(android)