1. 程式人生 > >ionic昇華過程8-cordova外掛+mui小案例

ionic昇華過程8-cordova外掛+mui小案例

一。mui簡介。

   MUI是一套前端框架,由DCLOUD公司研發而成,提供大量H5和js語言組成的元件,大大提高了開發效率,可以用於開發web端應用、web app等應用,中國比較流行的前端工具Hbuilder也是出自該公司 Hbuilder中整合mui。hbuilder提供了程式碼庫提示功能非常強大 官方演示(http://dev.dcloud.net.cn/mui/snippet/):

二 。案例演示。

製作一個簡單的 火山小視訊的demo 實現一個上滑重新整理獲取資料 點選右上角視訊 呼叫系統攝像頭功能(cordova) 效果圖如下

使用cordova建立一個專案

C:\Users\Administrator>cordova create hello1 cn.hello1 hello1
Creating a new cordova project.

使用hbuilder開啟目錄 開啟專案  專案上右鍵 轉換成移動app

在hbuilder新建一個移動專案  將 css和fonts和js中的檔案拷貝到www對應目錄

如果是使用vscode開發 
vscode安裝 cordovatools 開啟除錯視窗 點選配置開啟lauanch.json 列表很多選項 

Run Android on Devide 當手機插入 可以安裝到手機裝置
Run Android on emulator 執行程式在模擬器上
simulate Android on Browser 在瀏覽器上模擬android 

頁面繪製 就不談 直接給出原始碼 
home.html(首頁的子頁面)

<!DOCTYPE html>
<!--
    Licensed to the Apache Software Foundation (ASF) under one
    or more contributor license agreements.  See the NOTICE file
    distributed with this work for additional information
    regarding copyright ownership.  The ASF licenses this file
    to you under the Apache License, Version 2.0 (the
    "License"); you may not use this file except in compliance
    with the License.  You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing,
    software distributed under the License is distributed on an
    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
     KIND, either express or implied.  See the License for the
    specific language governing permissions and limitations
    under the License.
-->
<html>

	<head>
		<!--
        Customize this policy to fit your own app's needs. For more guidance, see:
            https://github.com/apache/cordova-plugin-whitelist/blob/master/README.md#content-security-policy
        Some notes:
            * gap: is required only on iOS (when using UIWebView) and is needed for JS->native communication
            * https://ssl.gstatic.com is required only on Android and is needed for TalkBack to function properly
            * Disables use of inline scripts in order to mitigate risk of XSS vulnerabilities. To change this:
                * Enable inline JS: add 'unsafe-inline' to default-src
        -->
		<!--<meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *; img-src 'self' data: content:;">
-->
		<!--<meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *;script-src * 'unsafe-inline'">-->
		<meta name="format-detection" content="telephone=no">
		<meta name="msapplication-tap-highlight" content="no" charset="utf-8">
		<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width">

		<script src="js/mui.min.js"></script>
		<link href="css/mui.min.css" rel="stylesheet" />
		<link rel="stylesheet" type="text/css" href="css/index.css">
		<script type="text/javascript" charset="utf-8">
			mui.init({
				pullRefresh: {
					container: "#refreshContainer", //下拉重新整理容器標識,querySelector能定位的css選擇器均可,比如:id、.class等
					up: {
						height: 50, //可選,預設50.觸發下拉重新整理拖動距離,
						auto: false, //可選,預設false.首次載入自動下拉重新整理一次
						contentrefresh: "正在重新整理...", //可選,正在重新整理狀態時,下拉重新整理控制元件上顯示的標題內容
						contentnomore:'沒有更多資料了',//可選,請求完畢若沒有更多資料時顯示的提醒內容; 
						callback: function() {
							var rthis=this;
							query(function(data){
								if(data.length==0){
									//沒有資料了 不能拉了
									rthis.endPullupToRefresh(true);
								}
								//資料載入完成將正在載入去掉 false表示還有資料可以繼續拉
								rthis.endPullupToRefresh(false);
							});
							//mui('#refreshContainer').pullRefresh().refresh(true);
							 //this.endPullupToRefresh(true); 沒有資料了 就呼叫這個函式
						} //必選,重新整理函式,根據具體業務來編寫,比如通過ajax從伺服器獲取新資料;
					}
				}
			});
			var requestServer="http://192.168.1.3:8888/";
			var start=0;
			var length=6;
			function query(fn){
				mui.ajax({
					url:requestServer+"list?start="+start+"&length="+length,
					crossDomain:true,
					dataType:'json',
					success:function(data){
						console.log(JSON.stringify(data));
						mui.each(data,function(index,item){
							if(index % 2!=0 ){
								return;
							}
							var imgPath=requestServer+"view?fileName=";
							var headerHtml="<div id='r_"+index+"' class='mui-row'>";
							var firstImage="<div id='r_"+index+"_c_0' class='mui-col-sm-6 mui-col-xs-6'>"+
							"	<li class='mui-table-view-cell imageView' style='background-image: url("+(imgPath+item.imageUrl)+");background-size: cover;'>"+
							"	<div style='font-size:15px;font-weight:bold;color:white;padding-bottom:180px;width:150%'>"+item.showTitle+"</div> "+
							"</li>"+
							"</div>";
							var secondImage="";
							if((index+1)<data.length){
								secondImage="<div id='r_"+index+"_c_1' class='mui-col-sm-6 mui-col-xs-6' >"+
								"	<li class='mui-table-view-cell imageView' style='background-image: url("+(imgPath+data[index+1].imageUrl)+");background-size: cover;'>"+
								"	<div style='font-size:15px;font-weight:bold;color:white;padding-top:180px;width:150%'>"+data[index+1].showTitle+"</div> "+
								"	</li>"+
								"</div>";
							}
						   var footHtml="</div>";
						   var newEle=headerHtml+firstImage+secondImage+footHtml;
						   mui("#contentView")[0].innerHTML=mui("#contentView")[0].innerHTML+newEle;
						   //var firstRowElement=mui("#r_"+index);
						   /*
						   var firstColElement=mui("#r_"+index+"_c_0")[0];
						   //算出第一個div顯示文字的文字 行離圓點的高度-20
						   var showTop=firstColElement.offsetTop+firstColElement.offsetHeight/12*11;
						   //離左側的距離 div離左側的距離+跨度的 1/5
						   var showLeft=firstColElement.offsetLeft+firstColElement.offsetWidth/20;
						   //debugger
						   var showDiv=document.createElement("div");
						   console.log(item.showTitle);
						   showDiv.innerHTML=item.showTitle;
						   //showDiv.style.backgroundColor="red";
						   //showDiv.style.borderStyle="1px solid green";
						   showDiv.style.position="absolute";
						   showDiv.style.fontWeight="bold";
						   showDiv.style.fontSize="15px";
						   showDiv.style.color="white";
						   console.log("#r_"+index+"_c_0"+showLeft+"----"+showTop);
						   
						   showDiv.style.left=showLeft+"px";
						   showDiv.style.top=showTop+"px";
						  
						   
						   showDiv.style.zIndex=100;
						    document.body.appendChild(showDiv);
						    **/
						})
						start+=6;
						if(fn)
							fn(data);
					}
				})
			}
			//初始化事件
			mui(function(){
				query();
				document.addEventListener("deviceready", onDeviceReady, false);
				function onDeviceReady() {
				    console.log(navigator.camera);
				    alert("chushihua");
				}
				//監聽點選事件
				mui("#camera")[0].addEventListener("tap",function(){
					alert("ggg");
				});
			})
		</script>
		<title>Hello World</title>
	</head>
 
	<body>
		<header class="mui-bar mui-bar-nav">
			<!--mui-row表示一行 MUI裡面也是使用的十二列的柵格系統。  mui-cos-xs-11佔用11格-->
			<div class="mui-row">
				<div class="mui-col-xs-2">
					<span class="mui-icon mui-icon-search"></span>

				</div>
				<div class="mui-col-xs-9">
					<div class="mui-row">
						<div class="mui-col-xs-4">
							<span class="mui-icon">視訊 </span>

						</div>
						<div class="mui-col-xs-4">
							<span class="mui-icon">直播</span>

						</div>
						<div class="mui-col-xs-4">
							<span class="mui-icon">同城</span>

						</div>
					</div>
				</div>

				<div class="mui-col-xs-1">
					<span id="camera" class="mui-icon mui-icon-camera"></span>
				</div>
			</div>

		</header>

		<div class="mui-content" >

			!--下拉重新整理容器-->
			<div id="refreshContainer" class="mui-content mui-scroll-wrapper" style="margin-top: 40px;">
				<div class="mui-scroll">
					<!--資料列表-->
					<ul id="contentView" class="mui-table-view mui-table-view-chevron">

						
						
					</ul>
				</div>
			</div>
		</div>

		
	</body>

</html>

index.html(工具欄 包含home.html)

<!DOCTYPE html>
<!--
    Licensed to the Apache Software Foundation (ASF) under one
    or more contributor license agreements.  See the NOTICE file
    distributed with this work for additional information
    regarding copyright ownership.  The ASF licenses this file
    to you under the Apache License, Version 2.0 (the
    "License"); you may not use this file except in compliance
    with the License.  You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing,
    software distributed under the License is distributed on an
    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
     KIND, either express or implied.  See the License for the
    specific language governing permissions and limitations
    under the License.
-->
<html>

	<head>
		<!--
        Customize this policy to fit your own app's needs. For more guidance, see:
            https://github.com/apache/cordova-plugin-whitelist/blob/master/README.md#content-security-policy
        Some notes:
            * gap: is required only on iOS (when using UIWebView) and is needed for JS->native communication
            * https://ssl.gstatic.com is required only on Android and is needed for TalkBack to function properly
            * Disables use of inline scripts in order to mitigate risk of XSS vulnerabilities. To change this:
                * Enable inline JS: add 'unsafe-inline' to default-src
        -->
		<!--<meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *; img-src 'self' data: content:;">
-->
		<meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *;script-src * 'unsafe-inline'">
		<meta name="format-detection" content="telephone=no">
		<meta name="msapplication-tap-highlight" content="no" charset="utf-8">
		<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width">

		<script src="js/mui.min.js"></script>
		<link href="css/mui.min.css" rel="stylesheet" />
		<link rel="stylesheet" type="text/css" href="css/index.css">
		<script type="text/javascript" charset="utf-8">
			mui.init({
			    subpages:[{
			      url:"home.html",//子頁面HTML地址,支援本地地址和網路地址
			      id:"myHome",//子頁面標誌
			      styles:{
			        top:'0px',//離頂部距離
        			bottom:'0px',//預設為0px,可不定義;
			        width:"100%",
			        height:"100%"
			      },
			      extras:{}//額外擴充套件引數
			    }]
			  });
		</script>
		<title>Hello World</title>
	</head>

	<body>
		
		<nav class="mui-bar mui-bar-tab">
			<a class="mui-tab-item mui-active">
				<span class="mui-icon mui-icon-home"></span>
				<span class="mui-tab-label">首頁</span>
			</a>
			<a class="mui-tab-item">
				<span class="mui-icon mui-icon mui-icon-personadd"></span>
				<span class="mui-tab-label">關注</span>
			</a>
			<a class="mui-tab-item" >
				<button type="button" style="margin-bottom: 10px;" class="mui-btn mui-btn-danger">+</button>
			</a>
			<a class="mui-tab-item">
				<span class="mui-icon mui-icon-email"></span>
				<span class="mui-tab-label">訊息</span>
			</a>
			<a class="mui-tab-item">
				<span class="mui-icon mui-icon-contact"></span>
				<span class="mui-tab-label">我的</span>
			</a>
		</nav>
	</body>

</html>

伺服器使用springboot專案 
主類

package cn.et;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
@SpringBootApplication
public class Example {

    @RequestMapping("/")
    String home() {
    	String url="https://restapi.amap.com/v3/weather/weatherInfo?city=440300&key=bab4c7212a804ba4abdca01fcbe55ae4";
    	String returnCode=restTemplate.getForEntity(url, String.class).getBody();
        return returnCode;
    }
    @Autowired
    RestTemplate restTemplate;

    @Bean
    public RestTemplate restTemplate() {
    	return new RestTemplate();
    }
    public static void main(String[] args) throws Exception {
        SpringApplication.run(Example.class, args);
    }

}

控制層 

package cn.et;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class PlayController {
	/**
	 * 測試資料
	 */
	static List<Player> playerList=new ArrayList();
	static {
		playerList.add(new Player("1","1.mp4","1.jpg","花叢中一朵野花 飄出好漂亮的藍色啊"));
		playerList.add(new Player("2","1.mp4","2.jpg","美女就是腿長長"));
		playerList.add(new Player("3","1.mp4","3.jpg","第一次出現這麼漂亮的豪車"));
		playerList.add(new Player("4","1.mp4","4.jpg","蠟筆小新的小屁屁 	"));
		playerList.add(new Player("5","1.mp4","5.jpg","明信片就應該這麼寫"));
		playerList.add(new Player("6","1.mp4","7.jpg","南瓜排隊萊羅"));
		playerList.add(new Player("7","1.mp4","8.jpg","意思意思啊 。。。"));
		playerList.add(new Player("8","1.mp4","9.jpg","中國鎮壓麼真強大啊"));
	}
	 public static void main(String[] args) {
		
	}
	 @ResponseBody
	 @RequestMapping("/list")
	 List<Player> home(Integer start,Integer length) {
		 int endIndex=start+length;
		 if(start>=playerList.size()) {
			 return new ArrayList<Player>();
		 }
		 if(playerList.size()<endIndex) {
			 endIndex=playerList.size();
		 }
		 return playerList.subList(start, endIndex);
     }
	 @RequestMapping("/view")
	 public void write(String fileName,HttpServletResponse response) throws IOException {
		InputStream is=this.getClass().getResourceAsStream("/myplayer/"+fileName);
		FileCopyUtils.copy(is, response.getOutputStream());
		is.close();
		response.flushBuffer();
	 }
	 
	 
	 
	 
}

實體類
 

package cn.et;

public class Player {
	private String playerId;
	private String playerUrl;
	private String imageUrl;
	private String showTitle;
	
	public Player(String playerId, String playerUrl, String imageUrl,String showTitle) {
		super();
		this.playerId = playerId;
		this.playerUrl = playerUrl;
		this.imageUrl = imageUrl;
		this.showTitle=showTitle;
	}
	public String getPlayerId() {
		return playerId;
	}
	public void setPlayerId(String playerId) {
		this.playerId = playerId;
	}
	public String getPlayerUrl() {
		return playerUrl;
	}
	public void setPlayerUrl(String playerUrl) {
		this.playerUrl = playerUrl;
	}
	public String getImageUrl() {
		return imageUrl;
	}
	public void setImageUrl(String imageUrl) {
		this.imageUrl = imageUrl;
	}
	public String getShowTitle() {
		return showTitle;
	}
	public void setShowTitle(String showTitle) {
		this.showTitle = showTitle;
	}
	
	
}

新增允許跨域的控制類

package cn.et;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Configuration
public class CorsConfig extends WebMvcConfigurerAdapter {
	public void addCorsMappings(CorsRegistry registry) {  
        registry.addMapping("/**")  
                .allowedOrigins("*")  
                .allowCredentials(true)  
                .allowedMethods("GET", "POST", "DELETE", "PUT")  
                .maxAge(3600);  
    }

}

home.html啟動時 傳送ajax到 /list 顯示列表 /view獲取圖片 具體讀取的圖片 在專案src/main/resources/mplayer

關於點選右側圖示 呼叫攝像頭的部分 使用命令 新增cordova的camera外掛

C:\Users\Administrator\hello>cordova plugin add cordova-plugin-camera
Unmet project requirements for latest version of cordova-plugin-camera:
    cordova-android (5.2.2 in project, >=6.3.0 required)
Fetching highest version of cordova-plugin-camera that this project supports: 2.4.1 (latest is 4.0.3)
Installing "cordova-plugin-camera" for android
Installing "cordova-plugin-compat" for android
Adding cordova-plugin-camera to package.json
Saved plugin info for "cordova-plugin-camera" to config.xml

因為是使用的android5.2.2 預設下載外掛都是最新版本的 該專案只支援 2.4.1 下載2.4.1

C:\Users\Administrator\hello>cordova plugin add [email protected]
Installing "cordova-plugin-camera" for android
Installing "cordova-plugin-compat" for android
Adding cordova-plugin-camera to package.json
Saved plugin info for "cordova-plugin-camera" to config.xml

使用cordova build android直接報錯

A problem occurred configuring root project 'android'.
> Could not resolve all dependencies for configuration ':_debugCompile'.
   > Could not find any version that matches com.android.support:support-v4:24.1.1+.
     Versions that do not match:
         26.1.0
         25.2.0
     Searched in the following locations:
         https://repo1.maven.org/maven2/com/android/support/support-v4/maven-metadata.xml
         https://repo1.maven.org/maven2/com/android/support/support-v4/
         https://jcenter.bintray.com/com/android/support/support-v4/maven-metadata.xml
     Required by:
         :android:unspecified

缺少android支援庫 android.support
android sdk的extras找到 所有android.support相關的庫 安裝

相關推薦

ionic昇華過程8-cordova外掛+mui案例

一。mui簡介。    MUI是一套前端框架,由DCLOUD公司研發而成,提供大量H5和js語言組成的元件,大大提高了開發效率,可以用於開發web端應用、web app等應用,中國比較流行的前端工具Hbuilder也是出自該公司 Hbuilder中整合mui。hbuilde

ionic昇華過程7-cordova工具

一。cordova簡介       Cordova 是使用HTML,CSS和JS構建移動應用的平臺。我們可以認為Cordova是一個工具,用於將我們的網路應用程式(javascript)與本機移動功能連線。預設情況下,Web應用程式不能直接呼叫本機移動功能。這就是Cordo

ionic昇華過程3-angularjs2入門

一。angular2js簡介 Angular2 是一款開源JavaScript庫,由Google維護,用來協助單一頁面應用程式執行。Angular2 是 Angular 1.x 的升級版本,效能上得到顯著的提高,能很好的支援 Web 開發元件。Angular2 釋出於201

ionic 呼叫自定義cordova外掛

ionic 作為一個跨平臺h5框架,收到越來越多的開發人員的歡迎,如何通過ionic去呼叫原生開發的SDK?可以通過 js 呼叫cordova 外掛的方式來實現。本文通過一個簡單的例子程式,來實現通過ionic 來呼叫 原生介面。該例子通過網頁開啟原生的的一個UIViewC

ionic專案中使用cordova外掛跳轉第三方地圖APP(百度、高德)

最近公司專案需要使用到地圖導航(當然你可以使用到地圖APP的其他功能),沒有合適的導航外掛,只能選擇跳轉第三方完成此功能,所使用外掛是cordova封裝外掛。 第一步,需要安裝的cordova外掛: cordova-plugin-device plugin for `

Ionic 跨平臺開發之Cordova外掛清單及使用說明

一,外掛相關常用命令1,檢視所有已經安裝的外掛     cordova plugin ls2,安裝外掛(以camera外掛為例)     cordova plugin add cordova-plugin-camera3,刪除外掛(以camera外掛為例)    cordov

Ionic2使用非ionic-native中的cordova外掛的方法

熟悉ionic1和angular1的使用者對於使用cordova都有一定的認識,但是在ionic2中官方給出的使用方法是從ionic-native這個npm包匯入要使用的cordova外掛。 例如: 使用ionic-native提供的AppVersion外掛

理解Ionic、Angular、Cordova外掛之間的關係

本文提及概念不區分Ionic 1/Angular 1和Ionic 2/Angular 2。 首先我們需要明確以下幾個概念: 1.即使我們將移動端web頁面做得和原生應用及其相似,在我們的頁面中也無法像原生應用那樣呼叫原生的能力,當然通過輸入框觸發鍵盤

ionic新增cordova外掛-NativeAudio

NativeAudio Cordova / PhoneGap 3.5 +本地音訊播放,針對HTML5遊戲和音訊應用所需的最小延遲,復調和併發。 cordova plugin add cordov

IonicCordova 外掛開發

操作命令 npm install -g plugman          //安裝plugman plugman create --name printPlug --plugin_id com.zmsoft.printPlug --plugin_version 0.0.1 

ionic新增cordova外掛-Device

Device 獲取裝置相關資訊,如平臺、裝置模型。 cordova plugin add cordova-plugin-device Example module.controller(

Ionic學習筆記七 Cordova 檔案下載外掛的使用

安裝: cordova plugin add cordova-plugin-file-transfer 1.5版本在使用中,可能遇到問題: file transfer error code

ioniccordova外掛,ping++方式 實現支付寶,微信支付

網上有類似的ionic ping++ 的例子,不過不太詳細,我是用.net 做的服務端介面,難道我們的net 要落伍了麼? 看來以後可能會收費的。準備先接入。 流程: /// <summary> ///

使用cordova外掛解決ionic頁面在手機上啟動出現黑頻問題

必要條件:安裝cordova環境 新增cordova-plugin-splashscreen外掛 在cordova專案中開啟cmd新增外掛 cordova plugin add cor

ionic和ionic2 環境下編寫自定義cordova外掛

1 增加android的平臺 對於一個ionic專案,在主目錄下通過以下命令列增加android平臺。 cordova platform add android 然後在platforms目錄下就會出現一個android資料夾: 之後可以使用配置了

ionic新增cordova外掛-ImagePicker

ImagePicker Cordova 外掛實現 iOS和Android 4及以上影象選擇器。 cordova plugin add cordova-plugin-image-picker 方

ioniccordova外掛自定義

外掛檔案目錄 外掛java類 package com.cool.toast; import org.apache.cordova.CallbackContext; import org.apa

ionic新增cordova外掛-SQLite

SQLite 呼叫SQLite本地資料庫儲存介面 cordova plugin add https://github.com/litehelpers/Cordova-sqlite-storag

Mysql儲存過程8:repeat循環

local cal 其他 host ted query code class pan 語法: repeat SQL until 條件 end repeat; 就是相當於其他語言中的: do{ # }while(); mys

解決VMware安裝Ubuntu的過程中窗口過無法看到按鈕的問題

round png eight idt wid ~~ vmware images 多人   最近在用VMware安裝Ubuntu的時候,發現竟然只能看到部分界面,鼠標拖拽也沒有用,就是看不到完整的界面,那要我怎麽按下一步啊~(真是哭笑不得%>_<%),或者按TA