// code which handles the action for each menu item public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.settings: { Intent preferences_intent = new Intent(); preferences_intent.setComponent( new ComponentName(download_photos.this, preferences.class)); preferences_intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); getApplicationContext().startActivity(preferences_intent); return true; } case R.id.logout: { try { download_photos.this.facebook.logout(getApplicationContext()); } catch (IOException e) { e.printStackTrace(); } mPrefs = getSharedPreferences("COMMON", MODE_PRIVATE); SharedPreferences.Editor editor = mPrefs.edit(); editor.putString("access_token", null); editor.putLong("access_expires", 0); editor.putBoolean("logout", true); editor.commit(); finish(); return true; } case R.id.about: { // shows our customized about dialog AboutDialog about = new AboutDialog(this); about.show(); return true; } // lets deal with default case default: return super.onOptionsItemSelected(item); } }
@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 :-) } }); } }