2016年5月14日 星期六

Android自訂返回鍵並且實作連續按兩下返回鍵退出程式

在MainActivity中增加以下程式:

 private static Boolean isExit = false;
private static Boolean hasTask = false;
Timer tExit;
TimerTask task;

@Overridepublic boolean onKeyDown(int keyCode, KeyEvent event)
{
    if (keyCode == KeyEvent.KEYCODE_BACK)
    {
        mAppWebView.loadUrl(mMenuURL); //自訂返回鍵按下後做的事情
        if(isExit==false)
        {
            isExit=true;
            Toast.makeText(this, "再按一次後退鍵退出應用程式",Toast.LENGTH_SHORT).show();
            if(!hasTask)
            {
                hasTask = true;
                tExit = new Timer();
                task = new TimerTask()
                {
                    @Override                    
                    public void run()
                    {
                        isExit = false;
                        hasTask = false;
                    }
                };
                tExit.schedule(task, 1000);
            }
        }
        else       
        {
            finish();
            System.exit(0);
        }
        return false;
    }
    return super.onKeyDown(keyCode, event);
}

Android webView 中的網址連結轉處理方式(呼叫開啟Assets中的檔案,開啟外部網址)

建立一個MyWebViewClient的Class file
在裡面的shouldOverrideUrlLoading方法中可以攔截到<a href="XXXXXX">中href指向的位址=>放在url!
檔案內容如下:

import android.content.Context;
import android.content.Intent;
import android.content.res.AssetManager;
import android.net.Uri;
import android.util.Log;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;


/** * Created by ray on 2016/5/14. */
public class MyWebViewClient extends WebViewClient {

    private Context context;

    public MyWebViewClient(Context context) {
        this.context = context;
    }

    @Override    public boolean shouldOverrideUrlLoading(WebView view, String url)
    {
        if(url.contains(".pdf") || url.contains(".doc"))
        {
            //處理取得純檔名(過濾掉路徑)            
            String[] fa = url.split("/");
            String filename = fa[fa.length-1];
            
            //將檔案從assets複製到SD card或手機內部儲存空間
            InputStream in = null;
            OutputStream out = null;
            AssetManager assetManager = this.context.getAssets();

            try {
                in = assetManager.open("app-land/file/"+filename);
                //注意路徑的前面不要有/
                File outFile = new File(this.context.getExternalFilesDir(null), filename);
                out = new FileOutputStream(outFile);
                copyFile(in, out);
            } catch(IOException e) {
                Log.e("tag", "Failed to copy asset file: " + filename, e);
            }
            finally {
                if (in != null) {
                    try {
                        in.close();
                    } catch (IOException e) {
                        // NOOP                    }
                }
                if (out != null) {
                    try {
                        out.close();
                    } catch (IOException e) {
                        // NOOP                    }
                }
            }
            //呼叫開啟詢問怎麼打開這個文件
            Intent intent = new Intent( Intent.ACTION_VIEW );

            File ff = new File(this.context.getExternalFilesDir(null)+"/"+filename);
            intent.setDataAndType(Uri.fromFile(ff), "application/*" );
            this.context.startActivity(intent);

            return true;
        }
        else if(url.contains("http"))
        {
            //開啟外部網址的處理
            Uri uriUrl = Uri.parse(url);
            Intent launchBrowser = new Intent(Intent.ACTION_VIEW, uriUrl);
            this.context.startActivity(launchBrowser);

            return true;
        }
        return super.shouldOverrideUrlLoading(view, url);
    }

    private void copyFile(InputStream in, OutputStream out) throws IOException
    {
        byte[] buffer = new byte[1024];
        int read;
        while((read = in.read(buffer)) != -1)
        {
            out.write(buffer, 0, read);
        }
    }
}
----------------------------------------------------
在MainActivity.java中的WebView部分程式加入以下的設定:
mAppWebView = (WebView) findViewById(R.id.webView);
mAppWebView.getSettings().setJavaScriptEnabled(true);
mAppWebView.getSettings().setSaveFormData(true);
mAppWebView.getSettings().setDatabaseEnabled(true);
mAppWebView.getSettings().setDomStorageEnabled(true);
mAppWebView.getSettings().setSupportZoom(true);
mAppWebView.getSettings().setAllowFileAccess(true);
mAppWebView.getSettings().setAllowContentAccess(true);
mAppWebView.setWebViewClient(new MyWebViewClient(this));//這一行!
mAppWebView.loadUrl(mAppURL);


---------------------------------------------------


最後是要在AndroidManifest.xml增加permission:



</application> <---放在這一行的後面哦!
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />