Android + HTML开发手机应用 demo 代码

最近在接触移动项目,为了能以后可以管理移动项目开发,得学点皮毛,自己也倒弄下android。

由于技术选型使用phoneGap+原生插件,前面学习使用phoneGap,总感觉以后会依赖phoneGap太深,毕竟phoneGap还是一个新的项目,很多效果还是原生的好,最后项目选择了完全原生开发,组里也进入了几个nb级别的人,但是看到他们做一些复杂应用的界面,还是很多界面细节需要程序员自己调整,费时费力,特别是前端界面改动频繁更是痛苦至极,故而又想到了HTML5做界面,毕竟HTML5来的快,前端就可以一条龙完成,但是又不想用phoneGap,从而有了自己这个demo的方案。

这个demo的界面不要挑剔瑕疵,我不会设计界面,只是自己的一点想法,结合原生和html5实现的。

大体目标是,通讯和算法,全部放于原生层,而主体界面展示交给HTML5。通过js互调完成数据交换。这样可以统一通讯接口,便于集成。

每个页面都会生成一个activity,过度效果都是原生界面,但是不需要开发很多Activity,而是一个或者几个就足够了,如下代码:代码下载

Activity:webview.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="
http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"  >
    <WebView
        android:id="@+id/webView"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:scrollbarStyle="insideOverlay" >
    </WebView>
</LinearLayout>

统一的Activity代码:

public class AccountActivity extends BaseWebViewActivitiy {
    @Override
    /** Called when the activity is first created. */
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        thisActivity = this;
        setContentView(R.layout.webview);
        initWebView(R.id.webView);

        Intent myIntent = getIntent();
        String page =  myIntent.getStringExtra("page");
        setupWebView(page);
    }

    private void setupWebView(String page) {
        webView.addJavascriptInterface(new JavaScriptInterface(), "caller");
        if("regist".equals(page)){
            loadurl(webView,"file:///android_asset/account/regist.html");
        }else if("forgetpassword".equals(page)){
            loadurl(webView,"file:///android_asset/account/forgetpassword.html");
        }else {
            isRoot = true;
            loadurl(webView,"file:///android_asset/account/login.html");
        }
       
    }
    private class JavaScriptInterface{
        @SuppressWarnings("unused")
        public void regist(){
            Intent myIntent = new Intent(AccountActivity.this, AccountActivity.class);
            myIntent.putExtra("page", "regist");
            AccountActivity.this.startActivity(myIntent);
        }
        @SuppressWarnings("unused")
        public void forgetPassword(){
            Intent myIntent = new Intent(thisActivity, AccountActivity.class);
            myIntent.putExtra("page", "forgetpassword");
            AccountActivity.this.startActivity(myIntent);
            //Toast.makeText(activityThis, tip, Toast.LENGTH_SHORT).show();  
        }
        @SuppressWarnings("unused")
        public void returnlast(){
            AccountActivity.this.finish();
        }
        @SuppressWarnings("unused")
        public void login(){
            UserStatus.getInst().setProfile(new UserProfile());
            Intent myIntent = new Intent(AccountActivity.this, UserActivity.class);
            //myIntent.putExtra("page", "home");
            AccountActivity.this.setResult(RESULT_OK);
            AccountActivity.this.finish ();
        }
    }
}

基类Activity:

public class BaseWebViewActivitiy extends Activity {
    protected WebView webView = null;
    protected Handler mHandler = new Handler();
    protected Activity thisActivity;
    private ProgressDialog pd;
    protected boolean isRoot = false;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    }

    protected void initWebView(int webview){
        webView = (WebView) findViewById(webview);
        mHandler=new Handler(){
            public void handleMessage(Message msg)
            {//定义一个Handler,用于处理下载线程与UI间通讯
              if (!Thread.currentThread().isInterrupted())
              {
                switch (msg.what)
                {
                case 0:
                    pd.show();//显示进度对话框           
                    break;
                case 1:
                    pd.hide();//隐藏进度对话框,不可使用dismiss()、cancel(),否则再次调用show()时,显示的对话框小圆圈不会动。
                    break;
                }
              }
              super.handleMessage(msg);
            }
        };
        webView.getSettings().setJavaScriptEnabled(true);
        webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
        webView.setWebViewClient(new WebViewClient(){  
            public boolean shouldOverrideUrlLoading(final WebView view, final String url) {
                loadurl(view,url);//载入网页
                return true;  
            }//重写点击动作,用webview载入
 
        });

        webView.setWebChromeClient(new WebChromeClient(){
            public void onProgressChanged(WebView view,int progress){//载入进度改变而触发
                 if(progress==100){
                    mHandler.sendEmptyMessage(1);//如果全部载入,隐藏进度对话框
                }  
                super.onProgressChanged(view, progress);  
            }  
        });
        pd=new ProgressDialog(thisActivity);
        pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        pd.setMessage("数据载入中,请稍候!");
       
    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {//捕捉返回键
        if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack()) {  
            webView.goBack();  
            return true;  
        }else if(keyCode == KeyEvent.KEYCODE_BACK){
            ConfirmExit();//按了返回键,但已经不能返回,则执行退出确认
            return true;
        }  
        return super.onKeyDown(keyCode, event);  
    }
    private void ConfirmExit(){//退出确认
        if(!isRoot){
            thisActivity.finish();//关闭activity
        }else{
            AlertDialog.Builder ad=new AlertDialog.Builder(thisActivity);
            ad.setTitle("退出");
            ad.setMessage("是否退出软件?");
            ad.setPositiveButton("是", new DialogInterface.OnClickListener() {//退出按钮
                public void onClick(DialogInterface dialog, int i) {
                    thisActivity.finish();//关闭activity
                }
            });
            ad.setNegativeButton("否",new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int i) {
                    //不退出不用执行任何操作
                }
            });
            ad.show();//显示对话框
        }
    }
    protected void loadurl(final WebView view,final String url){
        new Thread(){
            public void run(){
                mHandler.sendEmptyMessage(0);
                view.loadUrl(url);//载入网页
            }
        }.start();
    }
}

javaScript交互代码:

// JavaScript Document
$(function(){
    $("#btnReturnLogin").bind("click",function(){
        if($.os.android){
            window.caller.returnlast();
        //}else if($.os.ios){
        }else{
            window.open("login.html","_self");
        }
    });
    $("#btnRegist").bind("click",function(){
        if($.os.android){
            window.caller.regist();
        //}else if($.os.ios){
        }else{
            window.open("regist.html","_self");
        }
    });
    $("#btnForget").bind("click",function(){
        if($.os.android){
            window.caller.forgetPassword();
        //}else if($.os.ios){
        }else{
            window.open("forgetpassword.html","_self");
        }
    });
    $("#btnLogin").bind("click",function(){
        if($.os.android){
            window.caller.login();
        //}else if($.os.ios){
        }else{
            window.open("../user/payout.html","_self");
        }
    });
});

posted @ 2012-04-01 01:21  shareach  阅读(1361)  评论(0编辑  收藏  举报