WebView
查看网络是否连接、连接的方式是什么
网页加载失败时设置连接失败的页面
网络开始连接、正在连接和连接完成时进度条的设置
手势控制缩放
public class MainActivity extends Activity implements View.OnClickListener{
private TextView mTextViewDetail;
private TextView mTextViewError;
private Button mButtonGet;
private ConnectivityManager mConnectivityManager;
private WebView mWebView;
private ProgressBar mProgressBar;
private ZoomControls mZoomControl;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// mZoomControl = (ZoomControls) findViewById(R.id.zoomcontrol);
mProgressBar = (ProgressBar) findViewById(R.id.progressbar);
mTextViewDetail = (TextView) findViewById(R.id.textview_net_detail);
mButtonGet = (Button) findViewById(R.id.button_get_detail);
mButtonGet.setOnClickListener(this);
mConnectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
mWebView = (WebView) findViewById(R.id.webview);
mWebView.getSettings().setJavaScriptEnabled(true);// 允许加载JavaScript脚本语言。
mWebView.getSettings().setBuiltInZoomControls(true);//设置是否支持手势缩放
// mZoomControl.setOnZoomInClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View view) {
// mWebView.
// }
// });
// 因为其中有网页加载时的页面控制信息,主要是进度条控制
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);
mTextViewError.setText("网页加载失败");
}
});
// mWebView.setVisibility(View.GONE);
mWebView.loadUrl("http://www.oneplusbbs.com/");
}
@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_get_detail:
NetworkInfo info = mConnectivityManager.getActiveNetworkInfo();
if (info!=null&&info.isConnected()){
Toast.makeText(MainActivity.this,"有网络连接",Toast.LENGTH_SHORT).show();
mTextViewDetail.setText("网络连接的方式是:"+info.getTypeName());
}else {
Toast.makeText(MainActivity.this,"无网络连接",Toast.LENGTH_SHORT).show();
mTextViewDetail.setText("无网络连接");
}
break;
}
}
}
获取URL
网页点击跳转后,可以得到跳转后的URL,具体方法为view.getUrl(),如下所示:
public class MainActivity extends Activity implements OnClickListener{
private WebView mWebView;
String str;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
mWebView.getSettings().setJavaScriptEnabled(true);//让webview支持JavaScript脚本
mWebView.setWebViewClient(new WebViewClient(){
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// TODO Auto-generated method stub
view.loadUrl(url);
str = view.getUrl();//获取点击后得到的网页的URL
view.setVisibility(view.GONE);
Log.d("MainActivity", str);
return super.shouldOverrideUrlLoading(view, url);
}
});
mWebView.loadUrl("https://www.baidu.com");
}
}
URLConnection
连接服务器,得到服务器的HTML代码
public class MainActivity extends Activity implements View.OnClickListener {
private Button mButtonUrl;
private TextView mTextViewConnect;
private static final int URL_CONNECT = 0;
private Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
switch (msg.what){
case URL_CONNECT:
String text = (String) msg.obj;
mTextViewConnect.setText(text);
}
super.handleMessage(msg);
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mButtonUrl = (Button) findViewById(R.id.button_url);
mTextViewConnect = (TextView) findViewById(R.id.textview_connect);
mButtonUrl.setOnClickListener(this);
}
@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.button_url:
new Thread(new Runnable() {
@Override
public void run() {
connectServerlet();
}
}).start();
break;
}
}
private void connectServerlet() {
try {
// URL url = new URL("http://192.168.0.30:8080/MyWebTest/MyTestServlet");
URL url = new URL("http://www.360.com");
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);
buffer.append(line);
line = br.readLine();
}
Message msg = handler.obtainMessage();
msg.what = URL_CONNECT;
msg.obj = buffer.toString().trim();
handler.sendMessage(msg);
br.close();
is.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
下载文件
单线程下载
public class DownloadActivity extends Activity implements View.OnClickListener {
private Button mButtonSingle;
private Button mButtonMore;
private ProgressBar mProgressBarDown;
private int count = 0;
@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);
mProgressBarDown = (ProgressBar) findViewById(R.id.progressbar_down);
mButtonSingle.setOnClickListener(this);
mButtonMore.setOnClickListener(this);
}
@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.button_single:
DownloadTask task = new DownloadTask();
task.execute();
break;
case R.id.button_more:
break;
default:
break;
}
}
class DownloadTask extends AsyncTask<String,Integer,String>{
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
count = (int)(values[0]*100.0/values[1]);
mProgressBarDown.setProgress(count);
}
@Override
protected String doInBackground(String... strings) {
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(),"歌曲.mp3");
if (!file.exists()){
file.createNewFile();
}
FileOutputStream os = new FileOutputStream(file);
byte[] array = new byte[1024];
int sum = 0;
int index = is.read();
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;
}
}
}
多线程下载
public class MultiThread extends Thread {
private long start;
private long end;
private String urlPath;
private String filePath;
private int sum = 0;
public MultiThread(long start, long end, String urlPath, String filePath) {
this.start = start;
this.end = end;
this.urlPath = urlPath;
this.filePath = filePath;
}
public int getSum() {
return sum;
}
@Override
public void run() {
try {
URL url = new URL(urlPath);
URLConnection connection = url.openConnection();
connection.setRequestProperty("Range","bytes="+start+"-"+end);
InputStream is = connection.getInputStream();
byte[] array = new byte[1024];
is.read(array);
File file = new File(Environment.getExternalStorageDirectory(),"歌曲.mp3");
if (!file.exists()){
file.createNewFile();
}
RandomAccessFile randomAccessFile = new RandomAccessFile(file,"rw");
randomAccessFile.seek(start);
int index = is.read(array);
while (index!=-1){
randomAccessFile.write(array,0,index);
sum+=index;
index = is.read(array);
}
randomAccessFile.close();
is.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
super.run();
}
}
public class DownloadActivity extends Activity implements View.OnClickListener {
private Button mButtonSingle;
private Button mButtonMore;
private ProgressBar mProgressBarDown;
private int count = 0;
private int length;
private Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
switch (msg.what){
case 0x23:
mProgressBarDown.setProgress(msg.arg1*100/length);
break;
}
super.handleMessage(msg);
}
};
@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);
mProgressBarDown = (ProgressBar) findViewById(R.id.progressbar_down);
mButtonSingle.setOnClickListener(this);
mButtonMore.setOnClickListener(this);
}
@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.button_single:
DownloadTask task = new DownloadTask();
task.execute();
break;
case R.id.button_more://多线程下载
new Thread(new Runnable() {
@Override
public void run() {
String urlPath = "http:www.baidu.com/music/butong.mp3";
try {
URL url = new URL(urlPath);
URLConnection connection = url.openConnection();
length = connection.getContentLength();
File file = new File(Environment.getExternalStorageDirectory(),"song.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),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();
}
}
});
break;
default:
break;
}
}