Ejemplo n.º 1
0
 public static void init(Context context) {
   int version = getVersionCode(context);
   for (int i = 1; i < version; i++) {
     File file = context.getDir(i + "", Context.MODE_PRIVATE);
     deleteDirection(file);
   }
   mCacheDir = context.getDir(version + "", Context.MODE_PRIVATE);
 }
  public static void setup(Context c) {
    context = c;
    app_opt = context.getDir("opt", Context.MODE_WORLD_READABLE).getAbsoluteFile();
    app_log = context.getDir("log", Context.MODE_PRIVATE).getAbsoluteFile();
    app_home = context.getDir("home", Context.MODE_PRIVATE).getAbsoluteFile();
    app_gnupghome = context.getDir("gnupghome", Context.MODE_WORLD_WRITEABLE).getAbsoluteFile();
    environmentConf = new File(app_opt, "etc/environment.conf");
    versionFile = new File(app_opt, "VERSION");

    /*
     * MODE_WORLD_READABLE and MODE_WORLD_WRITEABLE were removed in Android
     * 4.3 (android-18) so force it that way. Yes, we really want this stuff
     * to be world read/write accessible since any app should be able to use
     * the command line tools
     */
    Posix.chmod("755", app_opt); // 755 is MODE_WORLD_READABLE
    Posix.chmod("773", app_gnupghome); // 773 is MODE_WORLD_WRITEABLE

    File bin = new File(app_opt, "bin");
    String logging = "--debug-level basic --log-file " + NativeHelper.app_log + "/gpg2.log ";
    gpg2 = new File(bin, "gpg2").getAbsolutePath() + " --no-tty --trust-model always " + logging;
    gpg_agent = new File(bin, "gpg-agent").getAbsolutePath();
    pinentry_android = new File(bin, "pinentry-android").getAbsolutePath();
    dirmngr = new File(bin, "dirmngr").getAbsolutePath();
    sdcard = Environment.getExternalStorageDirectory().getAbsolutePath();

    String lib = "";
    try {
      lib = new File(c.getApplicationInfo().nativeLibraryDir).getCanonicalPath();
    } catch (Exception e) {
      e.printStackTrace();
      lib = new File(c.getApplicationInfo().nativeLibraryDir).getAbsolutePath();
    }
    ldLibraryPath =
        lib + ":" + NativeHelper.app_opt + "/lib" + ":" + System.getenv("LD_LIBRARY_PATH");

    String path = System.getenv("PATH");
    envp =
        new String[] {
          "HOME=" + NativeHelper.app_home,
          "GNUPGHOME=" + NativeHelper.app_home,
          "LD_LIBRARY_PATH=" + ldLibraryPath,
          "PATH=" + path + ":" + bin.getAbsolutePath(),
          "app_opt=" + app_opt.getAbsolutePath()
        };

    log = new StringBuffer();
    constructEnvironmentConf();
    Log.i(TAG, "Finished NativeHelper.setup()");
  }
Ejemplo n.º 3
0
  public static void copyDataBase(SharedPreferences sharedPreferences) {

    try {
      logger.debug("Copie de base Magasins debutee");
      InputStream inStream = ctx.getResources().openRawResource(R.raw.poimeuge);
      byte[] buffer = new byte[inStream.available()];
      inStream.read(buffer);
      inStream.close();
      FileOutputStream fos =
          new FileOutputStream(
              ctx.getDir("databases", 0) + "/" + ctx.getString(R.string.database_file_interne),
              false);
      fos.write(buffer);
      fos.close();
      SharedPreferences.Editor editor = sharedPreferences.edit();
      editor.putBoolean(BundleTools.DATABASE_CHARGE, true);
      editor.commit();
      logger.debug("Fin de copie de base Magasins debutee");
    } catch (FileNotFoundException e) {
      logger.error("Fichier base non trouve");
    } catch (IOException e) {
      logger.error(
          String.format(
              "Fichier bizarre : %s non trouve", ctx.getString(R.string.database_file_interne)));
    }
  }
Ejemplo n.º 4
0
  /**
   * @param context Application context
   * @param directory The name of the directory
   * @param fName The name of the file
   * @param what The string to save
   * @param append True to append string to end of file, false to overwrite
   */
  public static void writeFile(
      Context context, String directory, String fName, String what, boolean append) {

    // This creates the directory if it doesn't exist...
    File dir = context.getDir(directory, Context.MODE_PRIVATE);
    if (dir == null) {
      Logging.debug(TAG, "writeFile:", "Error with " + directory);
      return;
    }

    try {
      File rf = new File(dir, fName);
      Logging.debug(TAG, "writeFile - routeFile = ", rf.getName() + ", " + rf.getAbsolutePath());
      FileOutputStream fOut = new FileOutputStream(rf, append);
      OutputStreamWriter writer = new OutputStreamWriter(fOut, "UTF-8");
      BufferedWriter fbw = new BufferedWriter(writer);
      fbw.write(what);
      fbw.newLine();
      fbw.flush();
      fbw.close();
      writer.close();
      fOut.close();
    } catch (IOException e) {
      Logging.debug(TAG, "writeFile:", e.getMessage());
      e.printStackTrace();
      throw new RuntimeException(e);
    }
  }
Ejemplo n.º 5
0
  /**
   * retrieve the auth token string securely
   *
   * @param context Context used to read storage
   * @return String of the stored access token, returns "" if no access token exists.
   */
  public static String getAccessToken(Context context) {
    String accessToken = "";
    String filename = getAccessTokenFilename(context.getApplicationContext());
    File authFile = context.getDir(filename, Context.MODE_PRIVATE);
    try {
      if (!authFile.exists()) {
        Log.e(
            AppBlade.LogTag, "Trying to create Authfile location : " + authFile.getAbsolutePath());
        authFile.mkdirs();
        authFile.createNewFile();
      }
      FileInputStream fis = context.openFileInput(filename);
      InputStreamReader inputStreamReader = new InputStreamReader(fis);
      BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
      accessToken = bufferedReader.readLine();
    } catch (Exception ex) {
      Log.w(AppBlade.LogTag, "Error creating Access Token ", ex);
    }
    if (!authFile.exists()) {
      Log.e(AppBlade.LogTag, "Did not create Authfile location : " + authFile);
    }

    Log.v(
        AppBlade.LogTag, String.format("getAccessToken File:%s, token:%s", filename, accessToken));
    return accessToken;
  }
Ejemplo n.º 6
0
  public static boolean decompressLibrary(Context context) {
    String libDir =
        context
            .getDir(XWalkLibraryInterface.PRIVATE_DATA_DIRECTORY_SUFFIX, Context.MODE_PRIVATE)
            .toString();
    File f = new File(libDir);
    if (f.exists() && f.isFile()) f.delete();
    if (!f.exists() && !f.mkdirs()) return false;

    long start = SystemClock.uptimeMillis();
    for (String library : MANDATORY_LIBRARIES) {
      try {
        Log.d(TAG, "Decompressing " + library);
        InputStream input = openRawResource(context, library);
        extractLzmaToFile(input, new File(libDir, library));
      } catch (Resources.NotFoundException e) {
        Log.d(TAG, library + " not found");
        return false;
      } catch (IOException e) {
        Log.e(TAG, e.getLocalizedMessage());
        return false;
      }
    }
    Log.d(TAG, "Time to decompress : " + (SystemClock.uptimeMillis() - start) + " ms");
    return true;
  }
Ejemplo n.º 7
0
 /** @return the private directory that is used to store application data. */
 @CalledByNative
 public static String getDataDirectory(Context appContext) {
   if (sDataDirectorySuffix == null) {
     throw new IllegalStateException(
         "setDataDirectorySuffix must be called before getDataDirectory");
   }
   return appContext.getDir(sDataDirectorySuffix, Context.MODE_PRIVATE).getPath();
 }
 @Override
 public boolean createDirectory(String name) {
   File dir = mContext.getDir(name, Context.MODE_PRIVATE);
   if (dir.exists()) {
     return true;
   }
   return false;
 }
Ejemplo n.º 9
0
  public File[] getListaBackupLogs(Context context) {
    this.contexto = context;
    File mydir = context.getDir("backup", Context.MODE_PRIVATE);
    File[] lista = mydir.listFiles();
    if (lista == null) {
      Log.d("COPIA DE SEGURIDAD", "Es mayor a cero");
    }

    return lista;
  }
Ejemplo n.º 10
0
  /**
   * 初始化目录
   *
   * @param context 上下文
   * @param currentUserId 当前用户ID
   */
  public static void initDirs(Context context, String currentUserId) {
    sAppRootDirPath = context.getDir(ROOT_DIR_NAME, Context.MODE_PRIVATE).getAbsolutePath();
    if (!TextUtils.isEmpty(currentUserId)) {
      sCurrentUserHomePath = sAppRootDirPath + File.separator + currentUserId;
      sCurrentUserConfigPath = sCurrentUserHomePath + File.separator + "config";
    }

    sDatabasePath = context.getDatabasePath(sDatabaseName).getAbsolutePath();
    sCurrentUserConfigPath = context.getDatabasePath("config").getAbsolutePath();
  }
  public FfmpegController(Context _context) throws FileNotFoundException, IOException {
    context = _context;
    fileBinDir = context.getDir("bin", 0);

    if (!new File(fileBinDir, libraryAssets[0]).exists()) {
      BinaryInstaller bi = new BinaryInstaller(context, fileBinDir);
      bi.installFromRaw();
    }

    ffmpegBin = new File(fileBinDir, "ffmpeg").getAbsolutePath();
  }
Ejemplo n.º 12
0
  private void setupJRuby(Activity startActivity) {
    System.setProperty("jruby.bytecode.version", "1.5");

    // enable proxy classes
    System.setProperty(
        "jruby.ji.proxyClassFactory", "com.rickbutton.rubydroid.DalvikProxyClassFactory");
    System.setProperty("jruby.ji.upper.case.package.name.allowed", "true");
    System.setProperty("jruby.class.cache.path", appContext.getDir("dex", 0).getAbsolutePath());

    // setup jruby home
    String apkName = getApkName();
    String jrubyHome = "file:" + apkName + "!/jruby.home";
    System.setProperty("jruby.home", jrubyHome);

    // configure jruby
    System.setProperty("jruby.compile.mode", "OFF"); // OFF OFFIR JITIR? FORCE FORCEIR
    // System.setProperty("jruby.compile.backend", "DALVIK");
    System.setProperty("jruby.bytecode.version", "1.6");
    System.setProperty("jruby.interfaces.useProxy", "true");
    System.setProperty("jruby.management.enabled", "false");
    System.setProperty("jruby.objectspace.enabled", "false");
    System.setProperty("jruby.thread.pooling", "true");
    System.setProperty("jruby.native.enabled", "false");
    System.setProperty("jruby.ir.passes", "LocalOptimizationPass,DeadCodeElimination");
    System.setProperty("jruby.backtrace.style", "normal"); // normal raw full mri

    ClassLoader loader = new PathClassLoader(apkName, RubySystem.class.getClassLoader());

    // disable gems
    RubyInstanceConfig config = new RubyInstanceConfig();
    config.setDisableGems(true);
    config.setLoader(loader);
    Ruby.newInstance(config);

    container =
        new ScriptingContainer(LocalContextScope.SINGLETON, LocalVariableBehavior.PERSISTENT);
    container.setClassLoader(loader);

    Thread.currentThread().setContextClassLoader(loader);

    if (appContext.getFilesDir() != null) {
      container.setCurrentDirectory(appContext.getFilesDir().getPath());
    }

    container.put("$package_name", appContext.getPackageName());

    container.put("app_context", appContext);
    container.put("system", this);
    rubyContext = container.runScriptlet(PathType.CLASSPATH, "ruby/droid/init.rb");

    Object mainActivity = container.get("MainActivity");
    container.callMethod(rubyContext, "start_ruby_activity", mainActivity, startActivity);
  }
Ejemplo n.º 13
0
 public PersonalScheduleDao(Context c) {
   log = new Logger(c);
   //		if(!Environment.MEDIA_UNMOUNTED.equals(Environment.getExternalStorageState())){
   //			System.out.println("存储卡已经被挂载,可以进行PersonalSchedule读写");
   //			File externalStorageDirectory = Environment.getExternalStorageDirectory();
   //			File f=new File(externalStorageDirectory,"GDOU/"+"PersonalSchedule");
   //			f.mkdir();
   //			psp=f.getAbsolutePath();
   //		}
   //		else{
   psp = c.getDir("PersonalSchedule", Context.MODE_APPEND).getAbsolutePath();
   //		}
   ps = new File(psp, "PersonalSchedule.bin");
 }
Ejemplo n.º 14
0
  /**
   * @param context Application context
   * @param directory The name of the directory
   * @param fName The name of the file
   * @return The saved routes if they exist, or an empty string otherwise.
   */
  public static String readFile(Context context, String directory, String fName) {

    BufferedReader in = null;
    File dir = context.getDir(directory, Context.MODE_PRIVATE);
    if (dir == null) {
      Logging.debug(TAG, "readFile:", "Context.getDir() failed");
      return new String();
    }

    File rf = new File(dir, fName);
    if (!rf.exists()) {
      Logging.debug(TAG, "readFile", rf.getAbsolutePath() + "/" + rf.getName() + " does NOT exist");
      return new String();
    }

    StringBuilder sb;

    try {
      InputStream inStream = new FileInputStream(rf);

      InputStreamReader inputreader = new InputStreamReader(inStream, "UTF-8");
      in = new BufferedReader(inputreader);

      String line;
      sb = new StringBuilder();

      line = in.readLine();

      while (line != null) {
        sb.append(line);
        line = in.readLine();
      }

      Logging.debug(TAG, "readFile - routeFile contents = ", sb.toString());

      return sb.toString();
    } catch (IOException e) {
      Logging.debug(TAG, "readFile:", e.getMessage());
    } finally {
      if (in != null) {
        try {
          in.close();
        } catch (IOException e) {
          Logging.debug(TAG, "readFile:", e.getMessage());
        }
      }
    }

    return new String();
  }
Ejemplo n.º 15
0
 public static String getRootDir() {
   File dir = Environment.getExternalStorageDirectory();
   String rootDir = null;
   if (dir == null) {
     dir = context.getDir(".", 0);
     rootDir = dir.getAbsolutePath();
   } else {
     rootDir = dir.getAbsolutePath() + "/" + context.getResources().getString(R.string.app_name);
   }
   dir = new File(rootDir);
   if (dir.mkdir()) {
     new File(rootDir + "/records").mkdir();
   }
   return rootDir;
 }
  /** Private constructor for this class. */
  private LibDexLoader() {
    String assetDexName = "jitsi-bundles-dex.jar";
    // Before the dex file can be processed by the DexClassLoader,
    // it has to be first copied from asset resource to a storage location.
    Context ctx = JitsiApplication.getGlobalContext();
    File dexInternalStoragePath = new File(ctx.getDir("dex", Context.MODE_PRIVATE), assetDexName);

    BufferedInputStream bis = null;
    OutputStream dexWriter = null;

    final int BUF_SIZE = 2 * 1024;
    try {
      bis = new BufferedInputStream(ctx.getAssets().open(assetDexName));
      dexWriter = new BufferedOutputStream(new FileOutputStream(dexInternalStoragePath));
      byte[] buf = new byte[BUF_SIZE];
      int len;
      while ((len = bis.read(buf, 0, BUF_SIZE)) > 0) {
        dexWriter.write(buf, 0, len);
      }
      dexWriter.close();
      bis.close();

      // Internal storage where the DexClassLoader writes
      // the optimized dex file to
      final File optimizedDexOutputPath = ctx.getDir("outdex", Context.MODE_PRIVATE);

      this.dexClassLoader =
          new DexClassLoader(
              dexInternalStoragePath.getAbsolutePath(),
              optimizedDexOutputPath.getAbsolutePath(),
              null,
              getClass().getClassLoader());
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }
Ejemplo n.º 17
0
  /**
   * Get instance of SharedPreferences by particular directory and name.
   *
   * @param context getSharedPreferences by context when the directory file is null
   * @param directoryFile The directory which is the parent of xml file
   * @param name The name of xml file
   * @param mod The permission of xml file for read or write
   * @return The instance of SharedPreferences
   * @throws ReasonException
   * @throws IllegalArgumentException
   */
  public static SharedPreferences getSharedPreferences(
      Context context, File directoryFile, String name, int mod) throws ReasonException {
    if (TextUtils.isEmpty(name)) {
      throw new IllegalArgumentException("Name must is not empty");
    }
    File tempFile = context.getDir("shared_prefs", Context.MODE_PRIVATE);
    if (directoryFile == null || directoryFile.equals(tempFile)) {
      return context.getSharedPreferences(name, mod);
    }
    if (!directoryFile.isDirectory()) {
      throw new IllegalArgumentException("directoryFile is not directory file");
    }
    if (!name.endsWith(".xml")) {
      name += ".xml";
    }
    File spFile = FileUtils.createFile(directoryFile, name, false);

    if (spFile == null || !spFile.exists()) {
      throw new RuntimeException(
          "Can not create target file[" + name + "]which parent is[" + directoryFile + "]");
    }
    synchronized (spReceiver) {
      String spKey = spFile.getAbsolutePath();
      SharedPreferences instance = spReceiver.get(spKey);
      if (instance == null) {
        try {
          Class<?> implCls = Class.forName("android.app.SharedPreferencesImpl");
          Constructor<?> cons = implCls.getDeclaredConstructor(File.class, int.class);
          cons.setAccessible(true);
          instance = (SharedPreferences) cons.newInstance(spFile, mod);
          spReceiver.put(spKey, instance);
        } catch (ClassNotFoundException e) {
          throw new ReasonException("Failed, because:" + e.getMessage());
        } catch (NoSuchMethodException e) {
          throw new ReasonException("Failed, because:" + e.getMessage());
        } catch (InstantiationException e) {
          throw new ReasonException("Failed, because:" + e.getMessage());
        } catch (IllegalAccessException e) {
          throw new ReasonException("Failed, because:" + e.getMessage());
        } catch (IllegalArgumentException e) {
          throw new ReasonException("Failed, because:" + e.getMessage());
        } catch (InvocationTargetException e) {
          throw new ReasonException("Failed, because:" + e.getMessage());
        }
      }
      return instance;
    }
  }
  /**
   * This method checks if the database directory is empty.
   *
   * @param context
   * @return
   */
  public static boolean isDBDirEmpty(Context context) {
    // There is no method in context that returns the database directory
    // without
    // having a database already created. creating the _temp folder ensures
    // the
    // applications root is returned even if the structure changes in a
    // future SDK
    File appRoot = context.getDir("_temp", Context.MODE_PRIVATE).getParentFile();
    File databaseDir = new File(appRoot, DATABASE_DIR);

    if (databaseDir.isDirectory() && databaseDir.list().length > 0) {
      return false;
    }

    return true;
  }
  /**
   * This method returns a file pointing at the directory that will contain the database files.
   *
   * <p>If the directory does not exist it will be created.
   *
   * @param context
   * @return
   */
  public static File getDatabaseDir(Context context) {
    // There is no method in context that returns the database directory
    // without
    // having a database already created. creating the _temp folder ensures
    // the
    // applications root is returned even if the structure changes in a
    // future SDK
    File appRoot = context.getDir("_temp", Context.MODE_PRIVATE).getParentFile();
    File databaseDir = new File(appRoot, DATABASE_DIR);

    if (!databaseDir.exists()) {
      databaseDir.mkdir();
    }

    return databaseDir;
  }
Ejemplo n.º 20
0
  @Override
  protected Integer doInBackground(String... params) {
    // 可能会受到 nosense 或者是超过限制的影响
    int ret = parseAdsResponse(mAdsJsonString);

    if (ret != NotifyAdsDef.RET_OK) {
      LogUtils.logProcess("广告解析失败 " + ret);
      return ret;
    }

    if (mAdsCell.showType == NotifyAdsDef.ADS_TYPE_NOTIFY) {
      ret = downloadXiaomiAds(mContext.getDir(NotifyAdsDef.ADS_FOLDER, Context.MODE_PRIVATE));
    }

    return ret;
  }
Ejemplo n.º 21
0
 public static GeckoProfile createGuestProfile(Context context) {
   if (context == null) {
     throw new IllegalArgumentException("context must be non-null");
   }
   try {
     File guestDir = context.getDir("guest", Context.MODE_PRIVATE);
     if (guestDir.exists()) guestDir.delete();
     guestDir.mkdir();
     GeckoProfile profile = get(context, "guest", guestDir);
     profile.mInGuestMode = true;
     return profile;
   } catch (Exception ex) {
     Log.e(LOGTAG, "Error creating guest profile", ex);
   }
   return null;
 }
Ejemplo n.º 22
0
  /**
   * Creates/retrieves a data directory in which the application can place its own custom data
   * files.
   *
   * @param privateStorage determines the location of the data directory. If this is true, the
   *     location is internal(app-data://), and external (SD) otherwise.
   * @return the data directory.
   */
  public File getDataDirectory(boolean privateStorage) {
    File f = null;
    Context context = softContext.get();
    if (context != null) {

      if (privateStorage) {
        f = context.getDir("appdata", 0);
      } else {
        File storageDir = Environment.getExternalStorageDirectory();
        f = new File(storageDir, context.getPackageName());
        if (!f.exists()) {
          f.mkdirs();
        }
      }
    }
    return f;
  }
  @Override
  protected Void doInBackground(Integer... params) {
    hour = params[0];
    minute = params[1];
    max_pic = params[2];

    File cacheDir = mContext.getCacheDir();
    File tmpDir = mContext.getDir("bc_tmp", Context.MODE_PRIVATE);

    if (!bForceCleanUp) {
      moveCachedFiles(hour, minute, cacheDir, tmpDir);
    }
    deleteExpiredCacheFiles();
    if (!bForceCleanUp) {
      moveCachedFiles(hour, minute, tmpDir, cacheDir);
    }

    return null;
  }
Ejemplo n.º 24
0
  /** Esta función permite verificar si una copia de seguridad de los logs sql contiene datos. */
  public boolean existeDatosCopiaSeguridad(Context context, String filename) {
    this.contexto = context;
    try {
      File mydir = context.getDir("backup", Context.MODE_PRIVATE);
      File f = new File(mydir, filename);
      if (f.exists()) {
        // verificar si el archivo posee datos
        if (f.length() > 0) {
          return true;
        }
      } else {
        Log.d("CHECK_EXIST_FILE_LOG", "No existe archivo de copia de seguridad");
      }
    } catch (Exception e) {
      e.printStackTrace();
    }

    return false;
  }
Ejemplo n.º 25
0
  /**
   * CreateExternalAdapter Tries to load an adapter class from foreign package
   *
   * @param String type - adapter type, also the suffix of the plugin application
   * @param String class_name - the adapter class name to be loaded
   * @param int dialog_id - resource ID to show dialog if the class can't be loaded
   */
  public static CommanderAdapter CreateExternalAdapter(
      Context ctx, String type, String class_name) {
    try {
      File dex_f = ctx.getDir(type, Context.MODE_PRIVATE);
      if (dex_f == null || !dex_f.exists()) {
        Log.w(TAG, "app.data storage is not accessable, trying to use the SD card");
        File sd = Environment.getExternalStorageDirectory();
        if (sd == null) return null; // nowhere to store the dex :(
        dex_f = new File(sd, "temp");
        if (!dex_f.exists()) dex_f.mkdir();
      }
      ApplicationInfo ai =
          ctx.getPackageManager().getApplicationInfo("com.ghostsq.commander." + type, 0);

      Log.i(TAG, type + " package is " + ai.sourceDir);

      ClassLoader pcl = ctx.getClass().getClassLoader();
      DexClassLoader cl = new DexClassLoader(ai.sourceDir, dex_f.getAbsolutePath(), null, pcl);
      //
      Class<?> adapterClass = cl.loadClass("com.ghostsq.commander." + type + "." + class_name);
      Log.i(TAG, "Class has been loaded " + adapterClass.toString());

      try {
        File[] list = dex_f.listFiles();
        for (int i = 0; i < list.length; i++) list[i].delete();
      } catch (Exception e) {
        Log.w(TAG, "Can't remove the plugin's .dex: ", e);
      }
      if (adapterClass != null) {
        Constructor<?> constr = null;
        try {
          constr = adapterClass.getConstructor(Context.class);
        } catch (Exception e) {
          e.printStackTrace();
        }
        if (constr != null) return (CommanderAdapter) constr.newInstance(ctx);
        else return (CommanderAdapter) adapterClass.newInstance();
      }
    } catch (Throwable e) {
      Log.e(TAG, "This class can't be created: " + type, e);
    }
    return null;
  }
Ejemplo n.º 26
0
  /**
   * Copies the data from the passed in Uri, to a new file for use with the Transfer Service
   *
   * @param context
   * @param uri
   * @return
   * @throws IOException
   */
  public static File copyContentUriToFile(Context context, Uri uri) throws IOException {
    InputStream is = context.getContentResolver().openInputStream(uri);
    File copiedData =
        new File(
            context.getDir("SampleImagesDir", Context.MODE_PRIVATE), UUID.randomUUID().toString());
    copiedData.createNewFile();

    FileOutputStream fos = new FileOutputStream(copiedData);
    byte[] buf = new byte[2046];
    int read = -1;
    while ((read = is.read(buf)) != -1) {
      fos.write(buf, 0, read);
    }

    fos.flush();
    fos.close();

    return copiedData;
  }
  public int killVideoProcessor(boolean asRoot, boolean waitFor) {
    int killDelayMs = 300;

    String ffmpegBin = new File(context.getDir("bin", 0), "ffmpeg").getAbsolutePath();

    int result = -1;

    int procId = -1;

    while ((procId = ShellUtils.findProcessId(ffmpegBin)) != -1) {

      Log.d(TAG, "Found PID=" + procId + " - killing now...");

      String[] cmd = {ShellUtils.SHELL_CMD_KILL + ' ' + procId + ""};

      try {
        result =
            ShellUtils.doShellCommand(
                cmd,
                new ShellCallback() {

                  @Override
                  public void shellOut(String msg) {

                    Log.d(TAG, "Killing ffmpeg:" + msg);
                  }

                  @Override
                  public void processComplete(int exitValue) {
                    // TODO Auto-generated method stub

                  }
                },
                asRoot,
                waitFor);
        Thread.sleep(killDelayMs);
      } catch (Exception e) {
      }
    }

    return result;
  }
Ejemplo n.º 28
0
  private void ReadDataStore() {
    appContext = MyApplication.getAppContext();

    dataStore = appContext.getSharedPreferences("DataStore", appContext.MODE_PRIVATE);
    dataEditor = dataStore.edit();
    d_isAlarmSetting = dataStore.getBoolean("isAlarmSet", false);
    d_dekiAlarmHour = dataStore.getInt("dekiAlarmTimeHour", -1);
    d_dekiAlarmMinutes = dataStore.getInt("dekiAlarmTimeMinutes", -1);
    d_yabaAlarmHour = dataStore.getInt("yabaAlarmTimeHour", -1);
    d_yabaAlarmMinutes = dataStore.getInt("yabaAlarmTimeMinutes", -1);

    // map情報を読み込み
    try {
      File file = new File(appContext.getDir("data", appContext.MODE_PRIVATE), "map");
      ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file));
      DOWMap = (HashMap) ois.readObject();
      LogUtil.LogString(DOWMap.toString());
    } catch (Exception e) {

    }
  }
 public static File a(String str, Context context, int i) {
   ql qlVar = a;
   new StringBuilder("getting dir for ").append(str).toString();
   String[] split = str.split("/");
   File dir = context.getDir(split[0], AccessibilityNodeInfoCompat.ACTION_PASTE);
   int i2 = 1;
   while (i2 < split.length) {
     if (i2 == split.length - 1) {
       File file = new File(dir, split[i2]);
       qlVar = a;
       new StringBuilder("returning file ").append(file.getAbsolutePath()).toString();
       return file;
     } else {
       i2++;
       dir = new File(dir, split[i2]);
     }
   }
   qlVar = a;
   new StringBuilder("returning file ").append(dir.getAbsolutePath()).toString();
   return dir;
 }
Ejemplo n.º 30
0
  /** start daemon */
  private static void start(Context context, Class<?> daemonClazzName, int interval) {
    String cmd =
        context.getDir(BIN_DIR_NAME, Context.MODE_PRIVATE).getAbsolutePath()
            + File.separator
            + DAEMON_BIN_NAME;

    /* create the command string */
    StringBuilder cmdBuilder = new StringBuilder();
    cmdBuilder.append(cmd);
    cmdBuilder.append(" -p ");
    cmdBuilder.append(context.getPackageName());
    cmdBuilder.append(" -s ");
    cmdBuilder.append(daemonClazzName.getName());
    cmdBuilder.append(" -t ");
    cmdBuilder.append(interval);

    try {
      Runtime.getRuntime().exec(cmdBuilder.toString()).waitFor();
    } catch (IOException | InterruptedException e) {
      Log.e(TAG, "start daemon error: " + e.getMessage());
    }
  }