@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.line_list); // Setup the list adapter = new IconAdapter<FileWrapper>(this, R.layout.line_list_item); ListView list = (ListView) findViewById(R.id.list); list.setAdapter(adapter); list.setOnItemClickListener(this); // Load Directory if (savedInstanceState != null) { backStack = savedInstanceState.getParcelableArrayList("BACKSTACK"); } if (backStack == null || backStack.size() == 0) { backStack = new ArrayList<BackStackItem>(); String startPath = (startDirectory == null || startDirectory.isEmpty()) ? Environment.getExternalStorageDirectory().getPath() : startDirectory; backStack.add(new BackStackItem(startPath, false)); } wrapFiles(); this.setVolumeControlStream(AudioManager.STREAM_MUSIC); }
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.c19_sdcard); mEdit = (EditText) findViewById(R.id.edittext); String ext = Environment.getExternalStorageState(); if (ext.equals(Environment.MEDIA_MOUNTED)) { mSdPath = Environment.getExternalStorageDirectory().getAbsolutePath(); } else { mSdPath = Environment.MEDIA_UNMOUNTED; } }
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.folderex); Intent gintent = getIntent(); getPath = gintent.getStringExtra("path"); dbPath = gintent.getStringExtra("dbpath"); FileList _FileList = new FileList(this); _FileList.setOnPathChangedListener(_OnPathChanged); _FileList.setOnFileSelected(_OnFileSelected); LinearLayout layout = (LinearLayout) findViewById(R.id.LinearLayout01); layout.addView(_FileList); Util.print("getPath = " + getPath); String path = " "; if (getPath.equals("empty")) { File root = Environment.getExternalStorageDirectory(); _FileList.setPath(root.getAbsolutePath()); path = root.getAbsolutePath(); } else { _FileList.setPath(getPath); path = getPath; } Util.print("path = " + path); _FileList.setFocusable(true); _FileList.setFocusableInTouchMode(true); ((TextView) findViewById(R.id.TextView01)).setSelected(true); }
public void mOnClick(View v) { switch (v.getId()) { case R.id.test: String rootdir = Environment.getRootDirectory().getAbsolutePath(); String datadir = Environment.getDataDirectory().getAbsolutePath(); String cachedir = Environment.getDownloadCacheDirectory().getAbsolutePath(); mEdit.setText( String.format( "ext = %s\nroot=%s\ndata=%s\ncache=%s", mSdPath, rootdir, datadir, cachedir)); break; case R.id.save: File dir = new File(mSdPath + "/dir"); dir.mkdir(); File file = new File(mSdPath + "/dir/file.txt"); try { FileOutputStream fos = new FileOutputStream(file); String str = "This file exists in SDcard"; fos.write(str.getBytes()); fos.close(); mEdit.setText("write success"); } catch (FileNotFoundException e) { mEdit.setText("File Not Found." + e.getMessage()); } catch (SecurityException e) { mEdit.setText("Security Exception"); } catch (Exception e) { mEdit.setText(e.getMessage()); } break; case R.id.load: try { FileInputStream fis = new FileInputStream(mSdPath + "/dir/file.txt"); byte[] data = new byte[fis.available()]; while (fis.read(data) != -1) {; } fis.close(); mEdit.setText(new String(data)); } catch (FileNotFoundException e) { mEdit.setText("File Not Found"); } catch (Exception e) {; } break; } }
private void checkAndLaunchUpdate() { Log.i(LOG_FILE_NAME, "Checking for an update"); int statusCode = 8; // UNEXPECTED_ERROR File baseUpdateDir = null; if (Build.VERSION.SDK_INT >= 8) baseUpdateDir = getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS); else baseUpdateDir = new File(Environment.getExternalStorageDirectory().getPath(), "download"); File updateDir = new File(new File(baseUpdateDir, "updates"), "0"); File updateFile = new File(updateDir, "update.apk"); File statusFile = new File(updateDir, "update.status"); if (!statusFile.exists() || !readUpdateStatus(statusFile).equals("pending")) return; if (!updateFile.exists()) return; Log.i(LOG_FILE_NAME, "Update is available!"); // Launch APK File updateFileToRun = new File(updateDir, getPackageName() + "-update.apk"); try { if (updateFile.renameTo(updateFileToRun)) { String amCmd = "/system/bin/am start -a android.intent.action.VIEW " + "-n com.android.packageinstaller/.PackageInstallerActivity -d file://" + updateFileToRun.getPath(); Log.i(LOG_FILE_NAME, amCmd); Runtime.getRuntime().exec(amCmd); statusCode = 0; // OK } else { Log.i(LOG_FILE_NAME, "Cannot rename the update file!"); statusCode = 7; // WRITE_ERROR } } catch (Exception e) { Log.i(LOG_FILE_NAME, "error launching installer to update", e); } // Update the status file String status = statusCode == 0 ? "succeeded\n" : "failed: " + statusCode + "\n"; OutputStream outStream; try { byte[] buf = status.getBytes("UTF-8"); outStream = new FileOutputStream(statusFile); outStream.write(buf, 0, buf.length); outStream.close(); } catch (Exception e) { Log.i(LOG_FILE_NAME, "error writing status file", e); } if (statusCode == 0) System.exit(0); }
@Override public void onResume() { super.onResume(); rootdir = Environment.getExternalStorageDirectory().getAbsolutePath(); directoryView = (TextView) findViewById(R.id.directory); SharedPreferences settings = getPreferences(0); String lastBrowsedDirectory = settings.getString("lastBrowsedDirectory", null); if (lastBrowsedDirectory == null) { lastBrowsedDirectory = rootdir; } loadDirectory(lastBrowsedDirectory); }
public void play() { try { mp.setDataSource( Environment.getExternalStorageDirectory() + "/pathofthefile/" + FirstSettings_two.file_video); mp.prepare(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalStateException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } mp.start(); }
public void onCreate() { int flags, screenLightVal = 1; Sensor mSensor; List<Sensor> sensors; if (scanData == null) return; // no ScanData, not possible to run correctly... PowerManager pm = (PowerManager) getSystemService(POWER_SERVICE); SP = PreferenceManager.getDefaultSharedPreferences(getBaseContext()); try { screenLightVal = Integer.parseInt(SP.getString("screenLight", "2")); } catch (NumberFormatException nfe) { } if (screenLightVal == 1) flags = PowerManager.PARTIAL_WAKE_LOCK; else if (screenLightVal == 3) flags = PowerManager.FULL_WAKE_LOCK; else flags = PowerManager.SCREEN_DIM_WAKE_LOCK; wl = pm.newWakeLock(flags, "OpenWLANMap"); wl.acquire(); while (myWLocate == null) { try { myWLocate = new MyWLocate(this); break; } catch (IllegalArgumentException iae) { myWLocate = null; } try { Thread.sleep(100); } catch (InterruptedException ie) { } } try { scanData.setUploadThres(Integer.parseInt(SP.getString("autoUpload", "0"))); } catch (NumberFormatException nfe) { } try { scanData.setNoGPSExitInterval( Integer.parseInt(SP.getString("noGPSExitInterval", "0")) * 60 * 1000); } catch (NumberFormatException nfe) { } Intent intent = new Intent(this, OWMapAtAndroid.class); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP); PendingIntent pendIntent = PendingIntent.getActivity(this, 0, intent, 0); notification = new NotificationCompat.Builder(this) .setSmallIcon(R.drawable.icon) .setContentTitle(getResources().getText(R.string.app_name)) .setContentText("") .setContentIntent(pendIntent) .build(); notification.flags |= Notification.FLAG_NO_CLEAR; notification.flags |= Notification.FLAG_ONGOING_EVENT; startForeground(1703, notification); getScanData().setService(this); getScanData().setmView(new HUDView(this)); getScanData().getmView().setValue(getScanData().incStoredValues()); WindowManager.LayoutParams params = new WindowManager.LayoutParams( WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY, WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE, PixelFormat.TRANSLUCENT); params.gravity = Gravity.LEFT | Gravity.BOTTOM; params.setTitle("Load Average"); WindowManager wm = (WindowManager) getSystemService(WINDOW_SERVICE); wm.addView(getScanData().getmView(), params); sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE); sensorManager.registerListener( this, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_GAME); sensorManager.registerListener( this, sensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION), SensorManager.SENSOR_DELAY_GAME); sensors = sensorManager.getSensorList(Sensor.TYPE_ACCELEROMETER); mSensor = sensors.get(0); getScanData().getTelemetryData().setAccelMax(mSensor.getMaximumRange()); telemetryDir = Environment.getExternalStorageDirectory().getPath() + "/telemetry/"; File dir = new File(telemetryDir); dir.mkdir(); connManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE); }
@Override protected String doInBackground(String... sUrl) { File folders = new File(Environment.getExternalStorageDirectory() + "/pathofthefile/"); folders.mkdirs(); File file; file = new File( Environment.getExternalStorageDirectory() + "/pathofthefile/" + FirstSettings_two.file_video); if (!file.exists()) { try { file.createNewFile(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { file.delete(); try { file.createNewFile(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } try { URL url = new URL(sUrl[0]); URLConnection connection = url.openConnection(); connection.connect(); // this will be useful so that you can show a typical 0-100% // progress bar int fileLength = connection.getContentLength(); // download the file InputStream input = new BufferedInputStream(url.openStream()); OutputStream output = new FileOutputStream(file); byte data[] = new byte[1024]; long total = 0; int count; while ((count = input.read(data)) != -1) { total += count; // publishing the progress.... publishProgress((int) (total * 100 / fileLength)); output.write(data, 0, count); } output.flush(); output.close(); input.close(); return "Downloaded"; } catch (Exception e) { // Toast.makeText(context, // "exeption",Toast.LENGTH_LONG).show(); return null; } }
@Override protected void onCreate(Bundle icicle) { Log.d("GODOT", "** GODOT ACTIVITY CREATED HERE ***\n"); super.onCreate(icicle); _self = this; Window window = getWindow(); window.addFlags( WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); // check for apk expansion API if (true) { boolean md5mismatch = false; command_line = getCommandLine(); boolean use_apk_expansion = false; String main_pack_md5 = null; String main_pack_key = null; List<String> new_args = new LinkedList<String>(); for (int i = 0; i < command_line.length; i++) { boolean has_extra = i < command_line.length - 1; if (command_line[i].equals("-use_apk_expansion")) { use_apk_expansion = true; } else if (has_extra && command_line[i].equals("-apk_expansion_md5")) { main_pack_md5 = command_line[i + 1]; i++; } else if (has_extra && command_line[i].equals("-apk_expansion_key")) { main_pack_key = command_line[i + 1]; SharedPreferences prefs = getSharedPreferences("app_data_keys", MODE_PRIVATE); Editor editor = prefs.edit(); editor.putString("store_public_key", main_pack_key); editor.commit(); i++; } else if (command_line[i].trim().length() != 0) { new_args.add(command_line[i]); } } if (new_args.isEmpty()) { command_line = null; } else { command_line = new_args.toArray(new String[new_args.size()]); } if (use_apk_expansion && main_pack_md5 != null && main_pack_key != null) { // check that environment is ok! if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { Log.d("GODOT", "**ERROR! No media mounted!"); // show popup and die } // Build the full path to the app's expansion files try { expansion_pack_path = Environment.getExternalStorageDirectory().toString() + "/Android/obb/" + this.getPackageName(); expansion_pack_path += "/" + "main." + getPackageManager().getPackageInfo(getPackageName(), 0).versionCode + "." + this.getPackageName() + ".obb"; } catch (Exception e) { e.printStackTrace(); } File f = new File(expansion_pack_path); boolean pack_valid = true; Log.d("GODOT", "**PACK** - Path " + expansion_pack_path); if (!f.exists()) { pack_valid = false; Log.d("GODOT", "**PACK** - File does not exist"); } else if (obbIsCorrupted(expansion_pack_path, main_pack_md5)) { Log.d("GODOT", "**PACK** - Expansion pack (obb) is corrupted"); pack_valid = false; try { f.delete(); } catch (Exception e) { Log.d("GODOT", "**PACK** - Error deleting corrupted expansion pack (obb)"); } } if (!pack_valid) { Log.d("GODOT", "Pack Invalid, try re-downloading."); Intent notifierIntent = new Intent(this, this.getClass()); notifierIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notifierIntent, PendingIntent.FLAG_UPDATE_CURRENT); int startResult; try { Log.d("GODOT", "INITIALIZING DOWNLOAD"); startResult = DownloaderClientMarshaller.startDownloadServiceIfRequired( getApplicationContext(), pendingIntent, GodotDownloaderService.class); Log.d("GODOT", "DOWNLOAD SERVICE FINISHED:" + startResult); if (startResult != DownloaderClientMarshaller.NO_DOWNLOAD_REQUIRED) { Log.d("GODOT", "DOWNLOAD REQUIRED"); // This is where you do set up to display the download // progress (next step) mDownloaderClientStub = DownloaderClientMarshaller.CreateStub(this, GodotDownloaderService.class); setContentView(com.godot.game.R.layout.downloading_expansion); mPB = (ProgressBar) findViewById(com.godot.game.R.id.progressBar); mStatusText = (TextView) findViewById(com.godot.game.R.id.statusText); mProgressFraction = (TextView) findViewById(com.godot.game.R.id.progressAsFraction); mProgressPercent = (TextView) findViewById(com.godot.game.R.id.progressAsPercentage); mAverageSpeed = (TextView) findViewById(com.godot.game.R.id.progressAverageSpeed); mTimeRemaining = (TextView) findViewById(com.godot.game.R.id.progressTimeRemaining); mDashboard = findViewById(com.godot.game.R.id.downloaderDashboard); mCellMessage = findViewById(com.godot.game.R.id.approveCellular); mPauseButton = (Button) findViewById(com.godot.game.R.id.pauseButton); mWiFiSettingsButton = (Button) findViewById(com.godot.game.R.id.wifiSettingsButton); return; } else { Log.d("GODOT", "NO DOWNLOAD REQUIRED"); } } catch (NameNotFoundException e) { // TODO Auto-generated catch block Log.d("GODOT", "Error downloading expansion package:" + e.getMessage()); } } } } initializeGodot(); // instanceSingleton( new GodotFacebook(this) ); }
@Override public void onCreate(Bundle savedInstanceState) { // locks the screen in portrait mode setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); super.onCreate(savedInstanceState); setContentView(R.layout.downloader); mtext = (TextView) findViewById(R.id.mtext); progress_text = (TextView) findViewById(R.id.progress_text); progress_download = (ProgressBar) findViewById(R.id.progress_download); // resume capability paused = false; resume_pause = (Button) findViewById(R.id.resume); // Create and launch the download thread downloadThread = new DownloadThread(this); downloadThread.start(); // Create the Handler. It will implicitly bind to the Looper // that is internally created for this thread (since it is the UI thread) handler = new Handler(); resume_pause.setOnClickListener( new View.OnClickListener() { public void onClick(View v) { if (!paused) { paused = true; resume_pause.setText("Resume"); // writeProgress(completed_downloads,total_files_to_download); downloadThread.requestStop(); downloadThread = null; } else { resume_pause.setText("Pause"); paused = false; initial_value = readProgress()[0]; final_value = links.size(); for (int i = initial_value; i < links.size(); i++) { downloadThread = new DownloadThread(download_photos.this); downloadThread.start(); downloadThread.enqueueDownload( new DownloadTask( links.get(i), path, i + 1, links.size(), download_photos.this)); } } } }); // load preferences for this activity mPrefs = getSharedPreferences("COMMON", MODE_PRIVATE); // This declaration is solely meant for reading the checkbox preference for downloading high res // pics. SharedPreferences dl_prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext()); // The global variable is set after reading the checkbox preference. dl_high_res_pics = dl_prefs.getBoolean("download_high_res", false); // load fb access token and its expiry values String access_token = mPrefs.getString("access_token", null); long expires = mPrefs.getLong("access_expires", 0); if (access_token != null) { facebook.setAccessToken(access_token); } if (expires != 0) { facebook.setAccessExpires(expires); } // get friend_name and album_name from the intent which started this activity Intent starting_intent = getIntent(); album_id = starting_intent.getStringExtra("id"); album_name = starting_intent.getStringExtra("name"); friend_name = starting_intent.getStringExtra("friend_name"); // real album and friend name may contain characters not suitable for file names. // regex pattern includes most of the invalid characters in file names legal_album_name = album_name.replaceAll("[.\\\\/:*?\"<>|]?[\\\\/:*?\"<>|]*", ""); legal_friend_name = friend_name.replaceAll("[.\\\\/:*?\"<>|]?[\\\\/:*?\"<>|]*", ""); // initialise the directory structure for download path = new File( Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/" + getText(R.string.app_name) + "/" + legal_friend_name + "/" + legal_album_name); if (dl_high_res_pics) path = new File(path.toString() + "/" + getText(R.string.folder_name_high_res)); resume_file = new File(path, "resume.txt"); // implements actions to done after receiving json object class meRequestListener extends BaseRequestListener { @Override public void onComplete(String response, Object state) { try { Log.i(TAG, response); json = Util.parseJson(response); // photos are in the form of a json array child = json.getJSONArray("data"); int total = child.length(); // contains links to photos links = new ArrayList<String>(total); // adds link to each photo to our list after replacing the "https" from url // DownloadManager does not support https in gingerbread for (int i = 0; i < total; i++) { photo_json = child.getJSONObject(i); if (dl_high_res_pics) { JSONArray image_set = photo_json.getJSONArray("images"); // highest resolution picture has the index zero in the images jsonarray JSONObject highest_res_pic = image_set.getJSONObject(0); String http_replaced = highest_res_pic.getString("source").replaceFirst("https", "http"); links.add(i, http_replaced); } else { // source property of the json object points to the photo's link String http_replaced = photo_json.getString("source").replaceFirst("https", "http"); links.add(i, http_replaced); } } download_photos.this.runOnUiThread( new Runnable() { public void run() { // mytask = new DownloadImageTask(); // mytask.execute(links); // start downloading using asynctask // new DownloadImageTask().execute(links); // downloadThread.setPath(path); // downloadThread.setWholeTasks(links.size()); if (resume_file.exists()) { initial_value = readProgress()[0]; final_value = links.size(); // case if the task is already completed if (initial_value == final_value) { completed = true; resume_pause.setVisibility(View.GONE); progress_download.setMax(final_value); progress_download.setProgress(0); // bug in progress bar progress_download.setProgress(initial_value); progress_text.setText("Completed."); mtext.setText( getText(R.string.download_textview_message_1) + " " + path.toString() + ". "); } // case if some of the photos are already downloaded else { progress_download.setMax(links.size()); // progress_download.setProgress(0); //bug in progress bar progress_download.setProgress(initial_value); // N.B if i= initial_value -1, then one image will be downloaded again. so to // save cost we start with i = initial_value for (int i = initial_value; i < links.size(); i++) { mtext.setText( getText(R.string.download_textview_message_1) + " " + path.toString() + ". "); // downloadThread.setRunningTask(i + 1); downloadThread.enqueueDownload( new DownloadTask( links.get(i), path, i + 1, final_value, download_photos.this)); } } } // case if the task is entirely new task else { for (int i = 0; i < links.size(); i++) { mtext.setText( getText(R.string.download_textview_message_1) + " " + path.toString() + ". "); // downloadThread.setRunningTask(i + 1); downloadThread.enqueueDownload( new DownloadTask( links.get(i), path, i + 1, links.size(), download_photos.this)); } } } }); } catch (JSONException ex) { Log.e(TAG, "JSONEXception : " + ex.getMessage()); } } } // makes asynchronous request to facebook graph api // the actions to be performed after receiving json response is implemented above Bundle parameters = new Bundle(); // facebook returns only 25 photos when limit is not specified. parameters.putString("limit", max_photos_in_album); if (!completed) mAsyncRunner.request(album_id + "/photos", parameters, new meRequestListener()); if (!facebook.isSessionValid()) { facebook.authorize( this, permissions, new DialogListener() { // save fb access token and its expiry values to prefernces of this activity @Override public void onComplete(Bundle values) { SharedPreferences.Editor editor = mPrefs.edit(); editor.putString("access_token", facebook.getAccessToken()); editor.putLong("access_expires", facebook.getAccessExpires()); editor.commit(); } @Override public void onFacebookError(FacebookError error) { Log.e(TAG, "Facebook Error : " + error.getMessage()); } @Override public void onError(DialogError e) { Log.e(TAG, e.getMessage()); } @Override public void onCancel() { // do nothing LOL :-) } }); } }