Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
//License from project: Apache License 

import android.content.Context;

import android.preference.PreferenceManager;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

public class Main {
    public static void checkStatus(Context context) {
        File defHosts = new File("/etc/hosts.og");
        File altHosts = new File("/etc/hosts.alt");
        File hosts = new File("/etc/hosts");
        try {
            if (PreferenceManager.getDefaultSharedPreferences(context).getInt("HFM_DISABLE_ADS", 0) == 1
                    && areFilesDifferent(hosts, altHosts)) {
                copyFiles(altHosts, hosts);
            } else if (PreferenceManager.getDefaultSharedPreferences(context).getInt("HFM_DISABLE_ADS", 0) == 0
                    && areFilesDifferent(hosts, defHosts) && isOurHostsFile()) {
                copyFiles(defHosts, hosts);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static boolean areFilesDifferent(File file1, File file2) throws IOException {
        String cr1, cr2;
        BufferedReader br1 = getBufferedReader(file1);
        BufferedReader br2 = getBufferedReader(file2);
        while ((cr1 = br1.readLine()) != null) {
            if ((cr2 = br2.readLine()) != null) {
                if (cr1.equals(cr2)) {
                    continue;
                }
            }
            return true;
        }
        return br2.readLine() != null;
    }

    public static void copyFiles(File srcFile, File dstFile) throws IOException {
        if (srcFile.exists() && dstFile.exists()) {
            String cmd = "mount -o rw,remount /system" + " && rm -f " + dstFile.getAbsolutePath() + " && cp -f "
                    + srcFile.getAbsolutePath() + " " + dstFile.getAbsolutePath() + " && chmod 644 "
                    + dstFile.getAbsolutePath() + " ; mount -o ro,remount /system";
            RunAsRoot(cmd);
        }
    }

    private static boolean isOurHostsFile() throws IOException {
        boolean ret = false;
        File hosts = new File("/etc/hosts");
        String line;
        BufferedReader rd1 = getBufferedReader(hosts);
        line = rd1.readLine();
        if (line.contains("#LiquidSmooth")) {
            ret = true;
        }
        return ret;
    }

    private static BufferedReader getBufferedReader(File file) throws IOException {
        return new BufferedReader(new FileReader(file));
    }

    public static void RunAsRoot(String string) throws IOException {
        Process P = Runtime.getRuntime().exec("su");
        DataOutputStream os = new DataOutputStream(P.getOutputStream());
        os.writeBytes(string + "\n");
        os.writeBytes("exit\n");
        os.flush();
    }
}