网络连接:MyNetwork
布局:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/textview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp"/>
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="网络连接"/>
<ProgressBar
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="20dp"
android:id="@+id/progressbar"/>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<WebView
android:id="@+id/webview"
android:layout_width="match_parent"
android:layout_height="match_parent">
</WebView>
<TextView
android:id="@+id/textview_erro"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"/>
</FrameLayout>
</LinearLayout>
权限:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
MainActivity
public class MainActivity extends Activity implements View.OnClickListener{
private Button mButton;
private TextView mTextView;
private ConnectivityManager mManager;
private WebView mWebView;//网页
private TextView mTextViewErro;//显示网页错误
private ProgressBar mProgressBar;//网页加载进度条
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mButton= (Button) findViewById(R.id.button);
mTextView= (TextView) findViewById(R.id.textview);
mWebView= (WebView) findViewById(R.id.webview);
mTextViewErro= (TextView) findViewById(R.id.textview_erro);
mProgressBar= (ProgressBar) findViewById(R.id.progressbar);
mButton.setOnClickListener(this);
mTextView.setOnClickListener(this);
mManager= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
mWebView.setWebViewClient(new WebViewClient());
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.setWebChromeClient(new WebChromeClient(){
@Override
public void onProgressChanged(WebView view, int newProgress) {
super.onProgressChanged(view, newProgress);
mProgressBar.setProgress(newProgress);//设置进度条
}
});
mWebView.setWebViewClient(new WebViewClient(){
//开始加载网页
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
mProgressBar.setVisibility(View.VISIBLE);//显示进度条
}
//网页加载完成
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
mProgressBar.setVisibility(View.INVISIBLE);//不显示进度条
}
@Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
super.onReceivedError(view, errorCode, description, failingUrl);
mWebView.setVisibility(View.GONE);
Toast.makeText(getApplicationContext(),"网页错误",Toast.LENGTH_LONG).show();
mTextViewErro.setText("加载失败");//设置textview文本内容
mTextViewErro.setVisibility(View.VISIBLE);//设置Textview可见
}
});
}
//返回上一页面,而不会直接退出程序
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(keyCode==KeyEvent.KEYCODE_BACK){
if(mWebView.canGoBack()){
mWebView.goBack();
return true;
}
}else {
MainActivity.this.finish();
}
return super.onKeyDown(keyCode, event);
}
@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.button:
// mWebView.loadUrl("ht2113tp://www.b24533355aidu.com");
mWebView.loadUrl("http://www.baidu.com");
// NetworkInfo info=mManager.getActiveNetworkInfo();
// if(info!=null&&info.isConnected()){
// Toast.makeText(getApplicationContext(),"有网络连接",Toast.LENGTH_LONG).show();
// mTextView.setText("网络连接为:"+info.getTypeName());
// }else {
// Toast.makeText(getApplicationContext(),"无网络连接",Toast.LENGTH_LONG).show();
// mTextView.setText("无网络连接");
// }
break;
default:
break;
}
}
}
显示网页:
正在加载时显示进度条:
加载完成后不显示进度条:
Webview:(网址错误时)
单线程、多线程下载
多线程下载图示:
NetworkDemo:
IndexActivity:(通过IndexActivity直接启动其他界面)
权限:
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"></uses-permission>
public class IndexActivity extends Activity implements View.OnClickListener {
private Button mButtonHttp;
private Button mButtonDownLoad;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_index);
mButtonHttp= (Button) findViewById(R.id.button_http);
mButtonDownLoad= (Button) findViewById(R.id.button_download);
mButtonHttp.setOnClickListener(this);
mButtonDownLoad.setOnClickListener(this);
}
@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.button_download:
Intent intent=new Intent(IndexActivity.this,DownloadActivity.class);
startActivity(intent);//启动线程下载界面
break;
case R.id.button_http:
Intent intent2=new Intent(IndexActivity.this,MainActivity.class);
startActivity(intent2);//启动URL连接界面
break;
}
}
}
MainActivity:(URL连接界面)
public class MainActivity extends Activity implements View.OnClickListener{
private Button mButton;
private TextView mTextView;
public static final int URL_CONTENT=0X23;
private Handler handler=new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what){
case URL_CONTENT:
String content= (String) msg.obj;
mTextView.setText(content);
break;
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mButton= (Button) findViewById(R.id.button);
mTextView= (TextView) findViewById(R.id.textview);
mButton.setOnClickListener(this);
}
@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.button:
new Thread(new Runnable() {
@Override
public void run() {
urlConnection();
}
}).start();
break;
default:
break;
}
}
public void urlConnection(){
try {
//URL url=new URL("http://www.360.com");
URL url=new URL("http://192.168.0.85:8080/JavaEE");
URLConnection connection=url.openConnection();
InputStream is=connection.getInputStream();
BufferedReader br=new BufferedReader(new InputStreamReader(is));
String line=br.readLine();
StringBuffer buffer=new StringBuffer();
while(line!=null){
Log.d("line",line);
buffer.append(line);
line=br.readLine();
}
Message message=handler.obtainMessage();
message.what=URL_CONTENT;
message.obj=buffer.toString().trim();
handler.sendMessage(message);
is.close();
br.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
URL url=new URL(“http://www.360.com“)
URL url=new URL(“http://192.168.0.85:8080/JavaEE“)
DownLoadActivity:
public class DownloadActivity extends Activity implements View.OnClickListener{
private Button mButtonSingle;
private ProgressBar mProgressBar;
private Button mButtonMore;
private static final int MESSAGE_THREAD=0X23;
private int length;
//多线程下载,用handler实现
private Handler handler=new Handler(){
@Override
public void handleMessage(Message msg) {
switch (msg.what){
case MESSAGE_THREAD:
mProgressBar.setProgress (msg.arg1*100/length);//设置多线程下载进度条
break;
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_download);
mButtonSingle= (Button) findViewById(R.id.button_single);
mProgressBar= (ProgressBar) findViewById(R.id.progressbar);
mButtonMore= (Button) findViewById(R.id.button_more);
mButtonSingle.setOnClickListener(this);
mButtonMore.setOnClickListener(this);
}
//AsynTask实现单线程下载
class MyTask extends AsyncTask<String,Integer,String>{
@Override
protected String doInBackground(String... strings) {
try {
URL url=new URL("http://192.168.0.85:8080/JavaEE/photo/view.png");
URLConnection connection=url.openConnection();
length=connection.getContentLength();
InputStream is=connection.getInputStream();
File file=new File(Environment.getExternalStorageDirectory(),"view.png");
if(!file.exists()){
file.createNewFile();
}
FileOutputStream os=new FileOutputStream(file);
byte[] array=new byte[1024];
int sum=0;
int i=is.read(array);
while(i!=-1){
os.write(array,0,i);
sum+=i;
publishProgress(sum,length);
i=is.read(array);
}
os.flush();
os.close();
is.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
mProgressBar.setProgress((int) (values[0]*100.0/values[1]));//设置单线程下载进度条
}
}
@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.button_single:
MyTask task=new MyTask();
task.execute();
break;
case R.id.button_more:
//多线程下载
new Thread(new Runnable() {
@Override
public void run() {
String urlPath="http://192.168.0.85:8080/JavaEE/photo/view.png";
try {
URL url=new URL(urlPath);
URLConnection connection=url.openConnection();
int length=connection.getContentLength();
File file=new File(Environment.getExternalStorageDirectory(),"a.png");
if(!file.exists()){
file.createNewFile();
}
MultiThread[] threads=new MultiThread[5];
for(int i=0;i<5;i++){
MultiThread thread=null;
if(i==4){
thread=new MultiThread(length/5*4,length,urlPath,file.getAbsolutePath());
}else {
thread=new MultiThread(length/5*i,length/5*(i+1),urlPath,file.getAbsolutePath());
}
thread.start();
threads[i]=thread;
}
boolean isFinish=true;
while(isFinish){
int sum=0;
for(MultiThread thread:threads){
sum+=thread.getSum();
}
Message message=handler.obtainMessage();
message.what=MESSAGE_THREAD;
message.arg1=sum;
handler.sendMessage(message);
if(sum+10>=length){
isFinish=false;
}
Thread.sleep(1000);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
break;
}
}
}
MultiThraed:(多线程下载)
public class MultiThread extends Thread {
private long start;
private long end;
private String urlPath;
private String filePath;
private int sum=0;
public int getSum() {
return sum;
}
public MultiThread(long start, long end, String urlPath, String filePath) {
this.start = start;
this.end = end;
this.urlPath = urlPath;
this.filePath = filePath;
}
@Override
public void run() {
try {
URL url=new URL(urlPath);
URLConnection connection=url.openConnection();
connection.setRequestProperty("Range","bytes="+start+"-"+end);
InputStream is=connection.getInputStream();
File file=new File(filePath);
if(!file.exists()){
file.createNewFile();
}
RandomAccessFile randomAccessFile=new RandomAccessFile(file,"rw");
randomAccessFile.seek(start);
byte[] array=new byte[1024];
int i=is.read(array);
while(i!=-1){
randomAccessFile.write(array,0,i);
sum+=i;
i=is.read(array);
}
randomAccessFile.close();
is.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
super.run();
}
}