|
@@ -1,14 +1,86 @@
|
|
|
package me.yoqi.android.nanohttpdemo;
|
|
|
|
|
|
+import android.content.Context;
|
|
|
+import android.content.Intent;
|
|
|
+import android.os.Bundle;
|
|
|
+import android.view.View;
|
|
|
+import android.webkit.WebResourceRequest;
|
|
|
+import android.webkit.WebSettings;
|
|
|
+import android.webkit.WebView;
|
|
|
+import android.webkit.WebViewClient;
|
|
|
+import android.widget.Button;
|
|
|
+
|
|
|
import androidx.appcompat.app.AppCompatActivity;
|
|
|
|
|
|
-import android.os.Bundle;
|
|
|
+import me.yoqi.android.nanohttpdemo.service.LocalService;
|
|
|
|
|
|
public class MainActivity extends AppCompatActivity {
|
|
|
+ Button btnStart;
|
|
|
+ WebView webView;
|
|
|
+ Context mContext;
|
|
|
+ boolean flag = false; //按钮 httpd 状态
|
|
|
|
|
|
@Override
|
|
|
protected void onCreate(Bundle savedInstanceState) {
|
|
|
super.onCreate(savedInstanceState);
|
|
|
setContentView(R.layout.activity_main);
|
|
|
+ mContext = this;
|
|
|
+ initView();
|
|
|
+ }
|
|
|
+
|
|
|
+ void initView() {
|
|
|
+ btnStart = findViewById(R.id.btn_starthttpd);
|
|
|
+ webView = findViewById(R.id.wv_main);
|
|
|
+ WebSettings webSettings = webView.getSettings();
|
|
|
+ webSettings.setJavaScriptEnabled(true);
|
|
|
+
|
|
|
+//设置自适应屏幕,两者合用
|
|
|
+ webSettings.setUseWideViewPort(true); //将图片调整到适合webview的大小
|
|
|
+ webSettings.setLoadWithOverviewMode(true); // 缩放至屏幕的大小
|
|
|
+
|
|
|
+//缩放操作
|
|
|
+ webSettings.setSupportZoom(true); //支持缩放,默认为true。是下面那个的前提。
|
|
|
+ webSettings.setBuiltInZoomControls(true); //设置内置的缩放控件。若为false,则该WebView不可缩放
|
|
|
+ webSettings.setDisplayZoomControls(false); //隐藏原生的缩放控件
|
|
|
+
|
|
|
+//其他细节操作
|
|
|
+ webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK); //关闭webview中缓存
|
|
|
+ webSettings.setAllowFileAccess(true); //设置可以访问文件
|
|
|
+ webSettings.setJavaScriptCanOpenWindowsAutomatically(true); //支持通过JS打开新窗口
|
|
|
+ webSettings.setLoadsImagesAutomatically(true); //支持自动加载图片
|
|
|
+ webSettings.setDefaultTextEncodingName("utf-8");//设置编码格式
|
|
|
+
|
|
|
+
|
|
|
+ btnStart.setOnClickListener(new View.OnClickListener() {
|
|
|
+ @Override
|
|
|
+ public void onClick(View v) {
|
|
|
+ if (!flag) {
|
|
|
+ startHttpd();
|
|
|
+ flag = true;
|
|
|
+ btnStart.setText("已启动");
|
|
|
+ webView.loadUrl("http://localhost:7600");
|
|
|
+ webView.setWebViewClient(new WebViewClient() {
|
|
|
+ @Override
|
|
|
+ public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
|
|
|
+ return super.shouldOverrideUrlLoading(view, request);
|
|
|
+ }
|
|
|
+ });
|
|
|
+ } else {
|
|
|
+ stopHttpd();
|
|
|
+ flag = false;
|
|
|
+ btnStart.setText("已关闭");
|
|
|
+ }
|
|
|
+ }
|
|
|
+ });
|
|
|
+ }
|
|
|
+
|
|
|
+ void startHttpd() {
|
|
|
+ Intent intent = new Intent(mContext, LocalService.class);
|
|
|
+ startService(intent);
|
|
|
+ }
|
|
|
+
|
|
|
+ void stopHttpd() {
|
|
|
+ Intent intent = new Intent(mContext, LocalService.class);
|
|
|
+ stopService(intent);
|
|
|
}
|
|
|
}
|