java中getinputstream_java – 如何停止HttpURLConnection.getInputStream()?

But if I call stopupload() while the code is handling at line is =

connection.getInputStream();,it still needs to wait for its reply.

从HoneyComb开始,所有网络操作都不允许在主线程上执行.为避免获得NetworkOnMainThreadException,您可以使用Thread或AsyncTask.

I want to stop waiting at once while implement stopupload(). How can I

do it?

以下代码让用户在2秒钟后停止上传,但您可以相应地修改睡眠时间(应少于5秒).

public void upload() {

try {

URL url = new URL(URLPath);

connection = (HttpURLConnection) url.openConnection();

connection.setConnectTimeout(30000);

connection.setReadTimeout(30000);

connection.setDoInput(true);

connection.setUseCaches(false);

connection.connect();

// run uploading activity within a Thread

Thread t = new Thread() {

public void run() {

is = connection.getInputStream();

if (is == null) {

throw new RuntimeException("stream is null");

}

// sleep 2 seconds before "stop uploading" button appears

mHandler.postDelayed(new Runnable() {

public void run() {

mBtnStop.setVisibility(View.VISIBLE);

}

},2000);

}

};

t.start();

} catch (Exception e) {

e.printStackTrace();

} finally {

if (is != null) {

try {

is.close();

} catch (IOException e) {

}

}

if (connection != null) {

connection.disconnect();

}

}

}

的onCreate:

@Override

public void onCreate(Bundle savedInstanceState) {

// more codes...

Handler mHandler = new Handler();

mBtnStop = (Button) findViewById(R.id.btn_stop);

mBtnStop.setBackgroundResource(R.drawable.stop_upload);

mBtnStop.setOnClickListener(mHandlerStop);

mBtnStop.setVisibility(View.INVISIBLE);

View.OnClickListener mHandlerStop = new View.OnClickListener() {

@Override

public void onClick(View v) {

stopUpload(); // called when "stop upload" button is clicked

}

};

// more codes...

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值