【目录】
怎样连接网络?
连接后台服务器
单线程文件下载
多线程文件下载
1、怎么连接网络(wifi,流量)
布局文件
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/network_detail"
android:layout_width="match_parent"
android:layout_height="30dp" />
<Button
android:id="@+id/button_getNetDetail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="获得网络连接状态" />
<ProgressBar
style="?android:attr/progressBarStyleHorizontal"
android:id="@+id/progressbar"
android:layout_width="match_parent"
android:layout_height="20dp"
android:visibility="invisible"/>
<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>//webview用来显示网页的内容
<TextView
android:id="@+id/textview_error"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:visibility="invisible"
android:text="网络连接错误"/>
</FrameLayout>
MainActivity
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private TextView mTextView;
private Button mButton;
private ConnectivityManager mConnectivityManager;//生命变量网络连接管理器
private WebView mWebView;
private TextView mTextViewError;
private ProgressBar mProgressbar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextView = (TextView) findViewById(R.id.network_detail);
mButton = (Button) findViewById(R.id.button_getNetDetail);
mTextViewError = (TextView) findViewById(R.id.textview_error);
mProgressbar = (ProgressBar) findViewById(R.id.progressbar);
mButton.setOnClickListener(this);
mConnectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);//网络连接管理器
mWebView = (WebView) findViewById(R.id.webview);
mWebView.getSettings().setJavaScriptEnabled(true); // 启用JavaScript
//下面几行用来实现放大缩小页面
mWebView.getSettings().setSupportZoom(true);//缩放开关设置此属性,
// 仅支持双击缩放,不支持触摸缩放(在android4.0是这样,其他平台没试过)
mWebView.getSettings().setBuiltInZoomControls(true);// 设置是否可缩放
mWebView.getSettings().setUseWideViewPort(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_SHORT).show();
;
mTextViewError.setText("加载失败");
mTextViewError.setVisibility(view.VISIBLE);
}
});
}
@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 v) {
switch (v.getId()){
case R.id.button_getNetDetail:
mWebView.loadUrl("http://www.baidu.com");//浏览百度
NetworkInfo info = mConnectivityManager.getActiveNetworkInfo();//得到网络连接的状态
if(info!=null&&info.isConnected()){
Toast.makeText(MainActivity.this,"有网络连接",Toast.LENGTH_SHORT).show();
mTextView.setText("网络连接状态为"+info.getTypeName());
}else{
Toast.makeText(MainActivity.this,"无网络连接",Toast.LENGTH_SHORT).show();
mTextView.setText("网络断开连接");
}
break;
}
}
}
2、连接后台服务器
public class NetworkActivity extends AppCompatActivity implements View.OnClickListener {
private Button mButton;
private Button mButtonDownload;
private TextView mTextView;
private Handler handler= new Handler(){//得到发送来的信息
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what){
case 0:
String content = (String) msg.obj;
mTextView.setText(content);
break;
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_network);
mTextView = (TextView) findViewById(R.id.textview);
mButton = (Button) findViewById(R.id.button_net);
mButton.setOnClickListener(this);
mButtonDownload = (Button) findViewById(R.id.button_download);
mButtonDownload.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button_net:
new Thread(new Runnable() {
@Override
public void run() {
connectionServerlet();//调用连接服务方法,如下
}
}).start();//定义新的线程并启动
break;
case R.id.button_download://点击下载按钮时启动DownLoadActivity
Intent intent = new Intent(NetworkActivity.this,DownLoadActivity.class);
startActivity(intent);
break;
}
}
private void connectionServerlet() {
try {
URL url = new URL("http://192.168.0.30:8080/MyWebTest/MyTestServerlet");//定义url,得到服务器后台的ip地址
URLConnection connection = url.openConnection();//打开url连接
//下面读url的内容
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);
buffer.append(line);//将读到的内容加到字符串buffer中
line = br.readLine();
}
Message msg = handler.obtainMessage();
msg.what = 0;//0是自定义的一个值,与上面得到的what值对应
msg.obj = buffer.toString().trim();
handler.sendMessage(msg);//调用方法,发送信息
br.close();
is.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
3、文件下载(单线程,多线程)
单线程
布局文件
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ProgressBar
android:id="@+id/progressbar"
style="@style/Base.Widget.AppCompat.ProgressBar.Horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="@+id/button_single"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="单线程下载" />
<Button
android:id="@+id/button_more"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="多线程下载" />
</LinearLayout>
</ScrollView>
- 关于ScrollView
一种可供用户滚动的层次结构布局容器,允许显示比实际多的内容。ScrollView是一种FrameLayout,意味需要在其上放置有自己滚动内容的子元素。子元素可以是一个复杂的对象的布局管理器。通常用的子元素是垂直方向的LinearLayout,显示在最上层的垂直方向可以让用户滚动的箭头。 只允许有一个子元素。
DownloadActivity
public class DownLoadActivity extends AppCompatActivity implements View.OnClickListener {
private Button mButtonSingle;
private Button mButtonMore;
private ProgressBar mProgressbar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_download);
mButtonSingle = (Button) findViewById(R.id.button_single);
mButtonMore = (Button) findViewById(R.id.button_more);
mProgressbar = (ProgressBar) findViewById(R.id.progressbar);
mButtonSingle.setOnClickListener(this);
mButtonMore.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.button_single:
SingleDownloadTask task = new SingleDownloadTask();//单线程下载
task.execute();
break;
case R.id.button_more:
break;
default:
break;
}
}
class SingleDownloadTask extends AsyncTask<String,Integer,String>{//继承AsyncTask,重写 doInBackground方法
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
mProgressbar.setProgress((int)(values[0]*100.0/values[1]));
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
@Override
protected String doInBackground(String... params) {
try {
URL url = new URL("http://192.168.0.30:8080/MyWebTest/music/aa.mp3");//得到下载文件的地址
URLConnection connection = url.openConnection();
int length = connection.getContentLength();
InputStream is = connection.getInputStream();//读
File file = new File(Environment.getExternalStorageDirectory(),"aa.mp3");//在sdcard中找到一个文件用来存放下载下来的内容
if(!file.exists()){
file.createNewFile();//如果没找到,新建一个文件
}
FileOutputStream os = new FileOutputStream(file);//写
byte[] array = new byte[1024];
int sum =0;
int index = is.read(array);//读数据
while (index!=-1){
os.write(array,0,index);//写入数据到文件
sum+=index;
publishProgress(sum,length);//更新进度条
index=is.read(array);
}
os.flush();
os.close();
is.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
}
要写一个MulityThread
public class MultiThread extends Thread {
public MultiThread(long start, long end, String url, String filePath) {
this.start = start;
this.end = end;
this.urlPath = url;
this.filePath = filePath;
}
private int sum = 0;
private long start;
private long end;
private String urlPath;
private String filePath;
public int getSum() {
return sum;
}
@Override
public void run() {
try {
URL url = new URL(urlPath);
URLConnection connection = url.openConnection();
connection.setAllowUserInteraction(true);
connection.setRequestProperty("Range", "bytes=" + start + "-"
+ end);
InputStream is = connection.getInputStream();
byte[] array = new byte[1024];
is.read(array);
File file = new File(filePath);
RandomAccessFile randomAccessFileile = new RandomAccessFile(file, "rw");
randomAccessFileile.seek(start);
int index = is.read(array);
while (index != -1) {
randomAccessFileile.write(array, 0, index);
sum += index;
index = is.read(array);
}
randomAccessFileile.close();
is.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
case R.id.button_more:
//多线程下载,activity中的点击事件
new Thread(new Runnable() {
@Override
public void run() {
try {
String urlPath = "http://192.168.0.30:8080/MyWebTest/music/aa.mp3";
URL url = new URL(urlPath);
URLConnection connection = url.openConnection();
length = connection.getContentLength();//得到文件的总长度
File file = new File(Environment.getExternalStorageDirectory(), "cc.mp3");
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) - 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 msg = handler.obtainMessage();
msg.what = 0x23;
msg.arg1 = sum;
handler.sendMessage(msg);
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;