是否有可能在没有Wifi的情况下运行.apk文件?

时间:2014-10-06 09:32:09

标签: android mobile wifi

我刚使用this创建了我网站的.apk文件。是否可以在不访问数据连接或wifi的情况下运行此文件?但同样,当Wifi或数据打开时,网站应该更新。任何人都有可以帮助我的东西吗?

1 个答案:

答案 0 :(得分:1)

首先将您网站的文件存储在资产文件夹

现在每次打开应用程序时,请检查网站文件是否存在,以防止应用程序崩溃。

下面给出的代码检查它是否存在,然后调用一个方法将文件从资产复制到设备存储。

File file = new File(YOUR FILE PATH);
if(!file.exists()){    
    //Doesn't exist. Create it in sdcard
    copyAssets();
}

以下是将网站文件从资产复制到设备存储的方法(将它们放入您的课程中) -

private void copyAssets() {

    AssetManager assetManager = getAssets();
    String[] files = null;

    try {

        files = assetManager.list("");

    } catch (IOException e) {
    Log.e("tag", "Failed to get asset file list.", e);
    }

    for(String filename : files) {
        InputStream in = null;
        OutputStream out = null;
        try {
            in = assetManager.open(filename);
            File outFile = new File(DIRECTORY, filename);
            out = new FileOutputStream(outFile);
            copyFile(in, out);
            in.close();
            in = null;
            out.flush();
            out.close();
            out = null;
        } catch(IOException e) {
            Log.e("tag", "Failed to copy asset file: " + filename, e);
        }       
    }
}

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);
    }
}

然后检查用户的互联网连接(在oncreate方法中) -

ConnectivityManager cm =
    (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {

    //user is connected to internet
    //put the code given ahead over here

}

许可 -

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

现在,如果用户已连接到互联网,请访问互联网并获取此类网站的新源代码(将此代码放入上面给出的互联网检查代码中) -

URL url = new URL(YOUR URL);
URLConnection yc = url.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
                                       yc.getInputStream(), "UTF-8"));
String inputLine;
StringBuilder a = new StringBuilder();
while ((inputLine = in.readLine()) != null)
    a.append(inputLine);
    in.close();

String source = a.toString();

现在有了源代码,请在设备存储中更新HTML文件,如下所示 -

File gpxfile = new File(File address, "filename.html");

BufferedWriter bW;

try {
    bW = new BufferedWriter(new FileWriter(gpxfile));
    bW.write(source); //our new source code
    bW.newLine();
    bW.flush();
    bW.close();
} catch (IOException e) {
    e.printStackTrace();
}

你完成了!现在从这样的存储器中将文件加载到webView(在我们之前编写的所有代码之后的oncreate方法中) -

  index.loadUrl("file://"+Environment.getExternalStorageDirectory()+ "Your address in storage");

建议不时发送用户请求打开互联网以更新网站,并防止使用过时的副本。