怎么做一个国外网站,wordpress程序,南通通州区网站制作,网络建设方案的调研照片实验六#xff1a;Android 的网络编程基础
6.1 实验目的
本次实验的目的是让大家熟悉 Android 开发中的如何获取天气预报#xff0c;包括了
解和熟悉 WebView、WebService 使用、网络编程事件处理等内容。
6.2 实验要求 熟悉和掌握 WebView 使用 了解 Android 的网络编程…实验六Android 的网络编程基础
6.1 实验目的
本次实验的目的是让大家熟悉 Android 开发中的如何获取天气预报包括了
解和熟悉 WebView、WebService 使用、网络编程事件处理等内容。
6.2 实验要求 熟悉和掌握 WebView 使用 了解 Android 的网络编程 熟悉和掌握 WebService 使用
6.3 实验内容
【练习 6.1】基于 Webview 的获取天气预报
1. 项目结构
项目名WebViewWeather
项目结构
res/layout/activity_main.xml主布局文件res/values/strings.xml字符串资源文件src/com/example/webview/MainActivity.java主Activity文件AndroidManifest.xmlAndroid清单文件
2. 主布局文件 (activity_main.xml)
?xml version1.0 encodingutf-8?
LinearLayout xmlns:androidhttp://schemas.android.com/apk/res/androidandroid:orientationverticalandroid:gravitycenter_horizontalandroid:layout_widthfill_parentandroid:layout_heightfill_parent!-- 按钮布局 --LinearLayoutandroid:orientationhorizontalandroid:layout_widthwrap_contentandroid:layout_heightwrap_content!-- 按钮北京 --Buttonandroid:idid/bjandroid:layout_widthwrap_contentandroid:layout_heightwrap_contentandroid:textstring/bjandroid:textSize30dp /!-- 按钮上海 --Buttonandroid:idid/shandroid:layout_widthwrap_contentandroid:layout_heightwrap_contentandroid:textstring/shandroid:textSize30dp /!-- 按钮哈尔滨 --Buttonandroid:idid/hebandroid:layout_widthwrap_contentandroid:layout_heightwrap_contentandroid:textstring/hebandroid:textSize30dp //LinearLayoutLinearLayoutandroid:orientationhorizontalandroid:layout_widthwrap_contentandroid:layout_heightwrap_content!-- 按钮广州 --Buttonandroid:idid/gzandroid:layout_widthwrap_contentandroid:layout_heightwrap_contentandroid:textstring/gzandroid:textSize30dp /!-- 按钮长春 --Buttonandroid:idid/ccandroid:layout_widthwrap_contentandroid:layout_heightwrap_contentandroid:textstring/ccandroid:textSize30dp /!-- 按钮沈阳 --Buttonandroid:idid/syandroid:layout_widthwrap_contentandroid:layout_heightwrap_contentandroid:textstring/syandroid:textSize30dpandroid:layout_gravityright //LinearLayout!-- WebView组件 --WebViewandroid:idid/webView1android:layout_widthmatch_parentandroid:layout_height0dipandroid:focusablefalseandroid:layout_weight1/
/LinearLayout3. 字符串资源文件 (strings.xml)
resourcesstring nameapp_nameWebViewWeather/stringstring namegoGO/stringstring namebj北京/stringstring namesh上海/stringstring namegz广州/stringstring nameheb哈尔滨/stringstring namecc长春/stringstring namesy沈阳/string
/resources4. 主Activity文件 (MainActivity.java)
package com.example.webviewweather;import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;public class MainActivity extends Activity implements OnClickListener {private WebView webView;Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);webView (WebView) findViewById(R.id.webView1);webView.getSettings().setJavaScriptEnabled(true);webView.setWebChromeClient(new WebChromeClient());webView.setWebViewClient(new WebViewClient());webView.loadUrl(http://m.weather.com.cn/mweather/);webView.setInitialScale(57 4);Button bj (Button) findViewById(R.id.bj);bj.setOnClickListener(this);Button sh (Button) findViewById(R.id.sh);sh.setOnClickListener(this);Button heb (Button) findViewById(R.id.heb);heb.setOnClickListener(this);Button cc (Button) findViewById(R.id.cc);cc.setOnClickListener(this);Button sy (Button) findViewById(R.id.sy);sy.setOnClickListener(this);Button gz (Button) findViewById(R.id.gz);gz.setOnClickListener(this);}Overridepublic void onClick(View view) {switch (view.getId()) {case R.id.bj:openUrl(101010100);break;case R.id.sh:openUrl(101020100);break;case R.id.heb:openUrl(101050101);break;case R.id.cc:openUrl(101060101);break;case R.id.sy:openUrl(101070101);break;case R.id.gz:openUrl(101280101);break;}}private void openUrl(String id) {webView.loadUrl(http://m.weather.com.cn/mweather/ id .shtml);}
}5. Android清单文件 (AndroidManifest.xml)
?xml version1.0 encodingutf-8?
manifest xmlns:androidhttp://schemas.android.com/apk/res/androidpackagecom.example.webview uses-permission android:nameandroid.permission.INTERNET/applicationandroid:allowBackuptrueandroid:iconmipmap/ic_launcherandroid:labelstring/app_nameandroid:supportsRtltrueandroid:themestyle/AppTheme activity android:name.MainActivity intent-filteraction android:nameandroid.intent.action.MAIN /category android:nameandroid.intent.category.LAUNCHER //intent-filter/activity/application
/manifest6.运行效果 【练习 6.2】基于 WebService 的手机归属地查询
1. 添加 ksoap2-android 库 在 ksoap2-android 的项目下载网站 下载 ksoap2-android-assembly-2.4-jar-with-dependencies.jar。 如果难以下载可以在随书光盘中找到该 JAR 包。 将下载的 ksoap2-android JAR 包添加到工程的 lib 目录下。 右键点击 JAR 包选择 “Add as library”将 ksoap2-android 集成到 Android 项目中。
2. WebService 配置 打开 http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx。 点击 “getMobileCodeInfo” 进入说明页获取以下关键信息 作用域 TargetNameSpace http://WebXml.com.cn/查询的方法名为 “getMobileCodeInfo”需要带上 “mobileCode” 与 “userID” 两个参数。返回的结果存在 “getMobileCodeInfoResult” 中。 在 http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx?wsdl 可以访问其 WSDL 说明。
3. 资源文件布局
创建 activity_web_client.xml 文件定义界面布局。
?xml version1.0 encodingutf-8?
LinearLayout xmlns:androidhttp://schemas.android.com/apk/res/androidxmlns:toolshttp://schemas.android.com/toolsandroid:layout_widthmatch_parentandroid:layout_heightmatch_parentandroid:paddingBottomdimen/activity_vertical_marginandroid:paddingLeftdimen/activity_horizontal_marginandroid:paddingRightdimen/activity_horizontal_marginandroid:paddingTopdimen/activity_vertical_marginandroid:orientationverticaltools:contextcom.example.webservicephonelocationlookup.WebClientLinearLayoutandroid:layout_widthmatch_parentandroid:layout_heightwrap_contentandroid:orientationhorizontalTextViewandroid:layout_widthwrap_contentandroid:layout_heightwrap_contentandroid:text输入手机号 /EditTextandroid:layout_width150dpandroid:layout_heightwrap_contentandroid:idid/etphone /Buttonandroid:layout_widthwrap_contentandroid:layout_heightwrap_contentandroid:text搜索android:idid/btnsearch //LinearLayoutTextViewandroid:layout_widthwrap_contentandroid:layout_heightwrap_contentandroid:text查询结果 /TextViewandroid:idid/tvinfoandroid:layout_widthwrap_contentandroid:layout_heightwrap_content/
/LinearLayout4. Java 代码
创建 WebClient.java 文件实现 WebService 调用逻辑。
package com.example.webservicephonelocationlookup;import android.os.AsyncTask;import androidx.appcompat.app.AppCompatActivity;import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;import org.ksoap2.SoapEnvelope;
import org.ksoap2.SoapFault;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParserException;import java.io.IOException;public class WebClient extends AppCompatActivity {private static final String SERVER_URL http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx?wsdl;private static final String NAMESPACE http://WebXml.com.cn/;private static final String METHOD_NAME getMobileCodeInfo;private EditText etPhone;private Button btnSearch;private TextView tvInfo;Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_web_client);etPhone (EditText) findViewById(R.id.etphone);btnSearch (Button) findViewById(R.id.btnsearch);tvInfo (TextView) findViewById(R.id.tvinfo);btnSearch.setOnClickListener(new View.OnClickListener() {Overridepublic void onClick(View v) {String phoneNumber etPhone.getText().toString();if (phoneNumber.length() 0) {getPhoneLocation(phoneNumber);}}});}private void getPhoneLocation(String phoneNumber) {new AsyncTaskString, Void, String() {Overrideprotected String doInBackground(String... params) {String location ;final HttpTransportSE httpSe new HttpTransportSE(SERVER_URL);httpSe.debug true;SoapObject soapObject new SoapObject(NAMESPACE, METHOD_NAME);soapObject.addProperty(mobileCode, params[0]);soapObject.addProperty(userID, );final SoapSerializationEnvelope envelope new SoapSerializationEnvelope(SoapEnvelope.VER10);envelope.setOutputSoapObject(soapObject);envelope.dotNet true;// 获取返回信息try {httpSe.call(NAMESPACE METHOD_NAME, envelope);if (envelope.getResponse() ! null) {SoapObject result (SoapObject) envelope.bodyIn;location result.getProperty(getMobileCodeInfoResult).toString();}} catch (XmlPullParserException | SoapFault | IOException e) {e.printStackTrace();}return location;}Overrideprotected void onPostExecute(String result) {tvInfo.setText(result);}}.execute(phoneNumber);}
}5. AndroidManifest.xml 配置
在 AndroidManifest.xml 中添加 INTERNET 权限。
uses-permission android:nameandroid.permission.INTERNET/配置应用程序的入口 Activity。
activity android:namecom.example.webservice.WebClientintent-filteraction android:nameandroid.intent.action.MAIN /category android:nameandroid.intent.category.LAUNCHER //intent-filter
/activity6. 运行效果
在模拟器或真机上运行应用程序输入手机号码点击搜索按钮查看查询结果。 【拓展】编写 Android 程序实现使用系统内置游览器打开指定网页。
步骤 1: 创建新项目
打开 Android Studio选择 “Start a new Android Studio project”。选择 “Empty Activity” 模板点击 “Next”。命名项目为 “WebBrowserDemo”选择语言为 “Java”点击 “Finish”。
步骤 2: 修改布局文件
打开 activity_main.xml 文件用以下代码替换其中的内容
?xml version1.0 encodingutf-8?
LinearLayout xmlns:androidhttp://schemas.android.com/apk/res/androidandroid:layout_widthfill_parentandroid:layout_heightfill_parentandroid:gravitycenter_horizontalandroid:orientationverticalEditTextandroid:idid/edandroid:layout_widthmatch_parentandroid:layout_height200px/EditTextButtonandroid:idid/bu1android:layout_width286dpandroid:layout_heightwrap_contentandroid:textGo /WebViewandroid:idid/webView1android:layout_widthmatch_parentandroid:layout_height0dipandroid:layout_weight1android:focusablefalse /
/LinearLayout步骤 3: 编写 Java 代码
打开 MainActivity.java 文件用以下代码替换其中的内容
package com.example.webbrowserdemo;import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;public class MainActivity extends Activity{private WebView webView; //声明 WebView 组件的对象String url;Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);webView(WebView)findViewById(R.id.webView1); //获取WebView 组件webView.getSettings().setJavaScriptEnabled(true); //设置 JavaScript可用webView.setWebChromeClient(new WebChromeClient()); //处理JavaScript 对话框webView.setWebViewClient(new WebViewClient()); //处理各种通知和请求事件如果不使用该句代码将使用内置浏览器访问网页webView.setInitialScale(57*4); //放网页内容放大 4 倍Button bu1(Button)findViewById(R.id.bu1);EditText editTextfindViewById(R.id.ed);bu1.setOnClickListener(new OnClickListener() {Overridepublic void onClick(View v) {urleditText.getText().toString();openUrl(url);}});}//打开网页的方法private void openUrl(String id){if (!url.equals()){webView.loadUrl(http://id/); //}else {Toast.makeText(this,网址不能为空,Toast.LENGTH_LONG).show();}}
}步骤 4: 运行应用 运行应用程序点击 “打开网页” 按钮。 系统将使用内置浏览器打开指定网页。
【拓展】编写 Android 程序实现从指定网站下载文件。
步骤 1: 创建新的 Android 项目
打开 Android Studio。选择 “Start a new Android Studio project”。选择 “Empty Activity” 模板然后点击 “Finish”。
步骤 2: 修改布局文件
打开 res/layout/activity_main.xml 文件并使用以下 XML 代码替换默认的布局
?xml version1.0 encodingutf-8?
RelativeLayout xmlns:androidhttp://schemas.android.com/apk/res/androidxmlns:toolshttp://schemas.android.com/toolsandroid:layout_widthmatch_parentandroid:layout_heightmatch_parenttools:context.MainActivityButtonandroid:idid/downloadButtonandroid:layout_widthwrap_contentandroid:layout_heightwrap_contentandroid:layout_centerInParenttrueandroid:text下载文件 /
/RelativeLayout步骤 3: 在 MainActivity.java 中添加代码
打开 MainActivity.java 文件修改 onCreate 方法和添加新的方法
package com.example.filedownloader;import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;import androidx.appcompat.app.AppCompatActivity;import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;public class MainActivity extends AppCompatActivity {private static final String DOWNLOAD_URL https://image.baidu.com/search/detail?ct503316480zundefinedtnbaiduimagedetailipndword%E7%99%BE%E5%BA%A6%E5%9B%BE%E7%89%87step_wordlid7733045057659531704ieutf-8incl2lm-1stundefinedhdundefinedlatestundefinedcopyrightundefinedcs505978886,3280506511os2821336839,1523677687simid3395585618,291075366pn0rn1di7264239678495129601ln1594frfmq1700213057065_Rfmicundefinedsundefinedsesmetab0widthundefinedheightundefinedfaceundefinedis0,0istype0istjitbdtype0spn0pi0gsm1eobjurlhttps%3A%2F%2Fp3.itc.cn%2Fq_70%2Fimages03%2F20211117%2F1270baf1c2f84fa19a99ef82c52d454c.pngrpstart0rpnum0adpicid0nojcundefineddyTabStrMCwxLDIsMyw2LDQsNSw4LDcsOQ%3D%3D;Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);Button downloadButton findViewById(R.id.downloadButton);downloadButton.setOnClickListener(new View.OnClickListener() {Overridepublic void onClick(View view) {new DownloadFileTask().execute(DOWNLOAD_URL);}});}private class DownloadFileTask extends AsyncTaskString, Void, Boolean {Overrideprotected Boolean doInBackground(String... urls) {String fileUrl urls[0];try {URL url new URL(fileUrl);HttpURLConnection urlConnection (HttpURLConnection) url.openConnection();urlConnection.connect();InputStream inputStream urlConnection.getInputStream();int totalSize urlConnection.getContentLength();int downloadedSize 0;byte[] buffer new byte[1024];int bufferLength;String fileName 示例图片.png; // 文件保存的名称FileOutputStream fileOutputStream new FileOutputStream(Environment.getExternalStorageDirectory().getPath() / fileName);while ((bufferLength inputStream.read(buffer)) 0) {fileOutputStream.write(buffer, 0, bufferLength);downloadedSize bufferLength;}fileOutputStream.close();return true;} catch (IOException e) {e.printStackTrace();return false;}}Overrideprotected void onPostExecute(Boolean result) {if (result) {Toast.makeText(MainActivity.this, 文件下载成功, Toast.LENGTH_SHORT).show();} else {Toast.makeText(MainActivity.this, 文件下载失败, Toast.LENGTH_SHORT).show();}}}
}步骤 4: 添加 Internet 和存储权限
确保在 AndroidManifest.xml 文件中添加了 Internet 和存储权限
uses-permission android:nameandroid.permission.INTERNET /
uses-permission android:nameandroid.permission.WRITE_EXTERNAL_STORAGE /步骤 5: 运行应用