目前有许多小企业在跨平台方面要做不同的企业级别的APP 但是研发成本又不够用,本人在业余时间编写了这个程序 希望对新手有帮助
移动端开发的大牛可以忽略这篇文章,也可以指点一二
文章内容纯手工原创仅供参考
直奔主题:
1.需要Gradel 引用第三方的包:
implementation 'org.jbundle.util.osgi.wrapped:org.jbundle.util.osgi.wrapped.org.apache.http.client:4.1.2'
2.配置权限
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
3.配置一个灵活的首页在本地的Sqllite
首先是数据库层面的编写 这里表名简单的设置成USER (可以根据自己的实际情况修改)
OrderDBHelper
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
/**
* Created by Jne
* Date: 2015/1/6.
*/
public class OrderDBHelper extends SQLiteOpenHelper {
private static final int DB_VERSION = 4;//数据库版本
private static final String DB_NAME = "modeldb";//数据库名
public static final String USER = "users";//用户表名
public OrderDBHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
try{
String sql = "CREATE TABLE IF NOT EXISTS "+USER+" (code text)";
sqLiteDatabase.execSQL(sql);
}catch (Exception e) {
Log.d("创建表异常", String.valueOf(e));
e.printStackTrace();
}
}
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) {
// String sql = "DROP TABLE IF EXISTS " + USER;
// String sql1 = "DROP TABLE IF EXISTS " + USER_HISTORY;
// sqLiteDatabase.execSQL(sql);
// sqLiteDatabase.execSQL(sql1);
onCreate(sqLiteDatabase);
}
}
OrderDao
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import com.yl.ylmodel.BaseApplication;
public class OrderDao {
public static void insertCode( String code){
try{
OrderDBHelper orderDBHelper = new OrderDBHelper(BaseApplication.getContext());
SQLiteDatabase db = orderDBHelper.getReadableDatabase();
String sqldel = "delete from "+ OrderDBHelper.USER;
db.execSQL(sqldel);
String sql = "insert into "+ OrderDBHelper.USER+" values('"+code+"')";
db.execSQL(sql);
db.close();
}catch (Exception e){
e.printStackTrace();
}
}
public static String getCode(){
String name = "";
try{
OrderDBHelper orderDBHelper = new OrderDBHelper(BaseApplication.getContext());
SQLiteDatabase db = orderDBHelper.getReadableDatabase();
String sql = "select * from "+ OrderDBHelper.USER;
Cursor cursor = db.rawQuery(sql, new String[0]);
if(cursor != null){
cursor.moveToNext();
name = cursor.getString(cursor.getColumnIndex("code"));
}
db.close();
}catch (Exception e){
e.printStackTrace();
}
return name;
}
}
BaseApplication 代码 需要在 AndroidManifest.xml 去绑定
<application
android:name=".BaseApplication"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".WebViewActivity"
android:screenOrientation="portrait">
</activity>
</application>
import android.app.Application;
import android.content.Context;
/**
* Created by ZhaoJunjie on 2019/7/12.
*/
public class BaseApplication extends Application {
private static Context mContext;
public void onCreate() {
super.onCreate();
mContext = getApplicationContext();
}
public static Context getContext(){
return mContext;
}
}
MainActivity 主程序入口
这里需要在后台做个Json接口 返回你需要的首页地址
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.yl.ylmodel.db.OrderDao;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
public class MainActivity extends UnitActivity {
private Button mButtonSubmit;
private EditText mEditTextCodeId;
@Override
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.activity_main);
super.onCreate(savedInstanceState);
if(OrderDao.getCode().equals("")){
new AlertDialog.Builder(MainActivity.this)
.setTitle("当前软件未激活")
.setMessage("请填写激活码")
.setPositiveButton("确定", null)
.show();
}else {
Intent intent = new Intent();
intent.setClass(MainActivity.this,WebViewActivity.class);
startActivity(intent);
}
}
@Override
public void requestOver(JSONObject jsonObject) {
super.requestOver(jsonObject);
try {
OrderDao.insertCode(jsonObject.getJSONObject("Code").getString("addvalue"));
Intent intent = new Intent();
intent.setClass(MainActivity.this,WebViewActivity.class);
startActivity(intent);
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public void initAllVIew() {
mButtonSubmit = (Button)findViewById(R.id.submit);
mEditTextCodeId = (EditText)findViewById(R.id.code_id);
super.initAllVIew();
}
@Override
public void initClick() {
super.initClick();
mButtonSubmit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
try {
Map<String,String> value = new HashMap<>();
value.put("code",mEditTextCodeId.getText().toString());
sendHttpRequest("你的请求地址",value);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
@Override
public void sendHttpRequest(String url, Map value) {
super.sendHttpRequest(url, value);
}
@Override
protected void onStart() {
super.onStart();
}
}
这里我做了一个工具 UnitActivity 代码如下
import android.app.Activity;
import android.app.AlertDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.widget.Toast;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;
import java.util.UUID;
/**
* Created by ZhaoJunjie on 2019/7/15.
*/
public class UnitActivity extends Activity {
public Handler mHandler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
try {
JSONObject resJson = new JSONObject(msg.obj.toString());
if(resJson.getString("respState").equals("00")){
requestOver(resJson);
}else {
new AlertDialog.Builder(UnitActivity.this)
.setTitle("验证激活码失败")
.setMessage(resJson.getString("respMessage"))
.setPositiveButton("确定", null)
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initAllVIew();
}
public void requestOver(JSONObject jsonObject){
}
public void initAllVIew(){
initClick();
}
public void initClick(){
}
public void sendHttpRequest(final String url, final Map value){
new Thread(new Runnable() {
@Override
public void run() {
Message message = new Message();
String res = post(url,value);
message.obj = res;
mHandler.sendMessage(message);
}
}).start();
}
//通用的的post请求用于传递文字参数
//
public static String post(String url, Map<String, String> params){
StringBuffer sb2 = null;
try {
String BOUNDARY = UUID.randomUUID().toString();
String PREFIX = "--", LINEND = "\r\n";
String MULTIPART_FROM_DATA = "multipart/form-data";
String CHARSET = "UTF-8";
URL uri = new URL(url);
HttpURLConnection conn = (HttpURLConnection) uri.openConnection();
conn.setReadTimeout(200000); // 缓存的最长时间
conn.setDoInput(true);// 允许输入
conn.setDoOutput(true);// 允许输出
conn.setUseCaches(false); // 不允许使用缓存
conn.setRequestMethod("POST");
conn.setRequestProperty("connection", "keep-alive");
conn.setRequestProperty("Charsert", "UTF-8");
conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA + ";boundary=" + BOUNDARY);
// 首先组拼文本类型的参数
StringBuilder sb = new StringBuilder();
for (Map.Entry<String, String> entry : params.entrySet()) {
sb.append(PREFIX);
sb.append(BOUNDARY);
sb.append(LINEND);
sb.append("Content-Disposition: form-data; name=\"" + entry.getKey() + "\"" + LINEND);
sb.append("Content-Type: text/plain; charset=" + CHARSET + LINEND);
sb.append("Content-Transfer-Encoding: 8bit" + LINEND);
sb.append(LINEND);
sb.append(entry.getValue());
sb.append(LINEND);
}
DataOutputStream outStream = new DataOutputStream(conn.getOutputStream());
outStream.write(sb.toString().getBytes());
// 请求结束标志
byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes();
outStream.write(end_data);
outStream.flush();
// 得到响应码
int res = conn.getResponseCode();
InputStream in = conn.getInputStream();
BufferedReader bf=new BufferedReader(new InputStreamReader(in,"UTF-8"));
//最好在将字节流转换为字符流的时候 进行转码
sb2 = new StringBuffer();
String line="";
while((line=bf.readLine())!=null){
sb2 .append(line);
}
// StringBuilder sb2 = new StringBuilder();
// if (res == 200) {
// int ch;
// while ((ch = in.read()) != -1) {
// sb2.append((char) ch);
// }
// }
outStream.close();
conn.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
return sb2.toString();
}
}
接下来就是浏览器的实现了
WebViewActivity
import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.Toast;
import com.yl.ylmodel.db.OrderDao;
/**
* Created by ZhaoJunjie on 2020/5/29.
*/
public class WebViewActivity extends Activity{
private WebView mWebView;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
setContentView(R.layout.activity_web_view);
super.onCreate(savedInstanceState);
mWebView = (WebView)findViewById(R.id.web_view);
WebSettings webSettings = mWebView.getSettings();
//如果访问的页面中要与Javascript交互,则webview必须设置支持Javascript
webSettings.setJavaScriptEnabled(true);
// 若加载的 html 里有JS 在执行动画等操作,会造成资源浪费(CPU、电量)
// 在 onStop 和 onResume 里分别把 setJavaScriptEnabled() 给设置成 false 和 true 即可
//支持插件
// webSettings.setPluginsEnabled(true);
webSettings.setPluginState(WebSettings.PluginState.ON);
//设置自适应屏幕,两者合用
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");//设置编码格式
mWebView.loadUrl(OrderDao.getCode());
//localStorage 允许存储
mWebView.getSettings().setDomStorageEnabled(true);
mWebView.getSettings().setAppCacheMaxSize(1024*1024*8);//存储的最大容量
String appCachePath = getApplicationContext().getCacheDir().getAbsolutePath();
mWebView.getSettings().setAppCachePath(appCachePath);
mWebView.getSettings().setAllowFileAccess(true);
mWebView.getSettings().setAppCacheEnabled(true);
}
@Override
public void onBackPressed() {
mWebView.goBack();
}
}
到此 简易的H5APP 框架就搭建成功了,后续会更新IOS版本的代码,欢迎指教!!!!