@Override protected Void doInBackground(ArrayList... params) { try { String fileLocation = String.valueOf(params[0].get(0)); String fileName = String.valueOf(params[0].get(1)); String folder = String.valueOf(params[0].get(2)); String path = Constants.ASSETS_IP + fileLocation + fileName; URL u = new URL(path); HttpParams httpParameters = new BasicHttpParams(); HttpURLConnection c = (HttpURLConnection) u.openConnection(); int timeoutConnection = 3000; int timeoutSocket = 5000; HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket); HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection); InputStream is = c.getInputStream(); FileOutputStream fos = new FileOutputStream(new File(folder + "/" + fileName)); int bytesRead = 0; byte[] buffer = new byte[4096]; while ((bytesRead = is.read(buffer)) != -1) { fos.write(buffer, 0, bytesRead); } fos.close(); is.close(); c.disconnect(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; }
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == Activity.RESULT_OK) { String sdStatus = Environment.getExternalStorageState(); if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) { // 检测sd是否可用 Log.i("TestFile", "SD card is not avaiable/writeable right now."); return; } String name = new DateFormat().format("yyyyMMdd_hhmmss", Calendar.getInstance(Locale.CHINA)) + ".jpg"; Toast.makeText(this, name, Toast.LENGTH_LONG).show(); Bundle bundle = data.getExtras(); Bitmap bitmap = (Bitmap) bundle.get("data"); // 获取相机返回的数据,并转换为Bitmap图片格式 FileOutputStream b = null; File file = new File("/sdcard/myImage/"); if (!file.exists()) file.mkdirs(); // 创建文件夹 String fileName = "/sdcard/myImage/" + name; File photofile = new File(fileName); if (!photofile.exists()) { try { photofile.createNewFile(); } catch (IOException e) { e.printStackTrace(); } } try { b = new FileOutputStream(photofile); bitmap.compress(Bitmap.CompressFormat.JPEG, 100, b); // 把数据写入文件 } catch (Exception e) { e.printStackTrace(); } finally { try { b.flush(); b.close(); } catch (IOException e) { e.printStackTrace(); } } // 动态的改变gridview中的一个Item的内容 bitmapList.set(currentIndex, bitmap); myGalleryAdapter.notifyDataSetChanged(); updatePhoto( Long.valueOf(phoneNumberToId.get(phoneNumber.get(currentIndex))), bitmapToBytes(bitmap)); // ((ImageView) findViewById(R.id.imageView)).setImageBitmap(bitmap);// // 将图片显示在ImageView里 Intent intent = new Intent(ContactActivity.this, ContactActivity.class); this.startActivity(intent); this.finish(); } }
/* * for using internal memory for data storage */ @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.getdatafrmsharedpref); try { initial(this); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
public int[] readProgress() { int progress[] = new int[2]; try { DataInputStream in = new DataInputStream(new BufferedInputStream(new FileInputStream(resume_file))); progress[0] = in.readInt(); progress[1] = in.readInt(); in.close(); } catch (FileNotFoundException e) { Log.e(TAG, "readProgress file not found."); } catch (IOException e) { Log.e(TAG, e.getMessage()); } return progress; }
// 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 String doInBackground(String... arg0) { // TODO Auto-generated method stub String data = null; FileInputStream fis = null; for (int i = 0; i < 25; i++) { // referencing progressupdate method publishProgress(4); try { Thread.sleep(100); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } dial.dismiss(); try { fis = openFileInput(FILENAME); byte[] arr = new byte[fis.available()]; // getting number of bytes in fis while (fis.read(arr) != -1) ; // reading the bytes in fis { data = new String(arr); } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { fis.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return data; }
@Override public void onClick(View v) { // TODO Auto-generated method stub switch (v.getId()) { // save button case R.id.bspref1: String str = getd.getText().toString(); /* File f=new File(FILENAME); try { fos=new FileOutputStream(f); fos.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } */ try { fos = openFileOutput(FILENAME, Context.MODE_PRIVATE); fos.write(str.getBytes()); fos.close(); } catch (FileNotFoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } break; // load button case R.id.bspref2: new LoadStuff().execute(FILENAME); break; } }
public void nextLevel() { boolean loaded = false; final GameBoard boardView = (GameBoard) this.findViewById(R.id.gameBoard); this.level++; AssetManager am = getResources().getAssets(); try { List<String> allTutoLevels = new LinkedList<String>(Arrays.asList(am.list("levels/tutorial"))); // if(addMsg){ // allTutoLevels.addAll(Arrays.asList(am.list("msg"))); // } Log.d(TAG, allTutoLevels.toString()); for (String name : allTutoLevels) { if (name.startsWith(this.level + ".")) { BufferedReader br = new BufferedReader(new InputStreamReader(am.open("levels/tutorial/" + name))); String line; String levelJSON = ""; while ((line = br.readLine()) != null) { levelJSON += line + "\n"; } br.close(); game.initGame( levelJSON, boardView.getMeasuredWidth() / 60, boardView.getMeasuredHeight() / 60); loaded = true; } } } catch (IOException e) { e.printStackTrace(); } if (!loaded) { Random r = new Random(); List<String> allLevels = new ArrayList<>(); try { allLevels = Arrays.asList(am.list("levels")); } catch (IOException e) { } if (r.nextBoolean() && !allLevels.isEmpty() && allLevels.size() != allDoneLevels.size()) { try { int nLevel; do { nLevel = r.nextInt(allLevels.size()); } while (allDoneLevels.contains(allLevels.get(nLevel))); String name = allLevels.get(nLevel); BufferedReader br = new BufferedReader(new InputStreamReader(am.open("levels/" + name))); String line; String levelJSON = ""; while ((line = br.readLine()) != null) { levelJSON += line + "\n"; } br.close(); allDoneLevels.add(name); game.initGame( levelJSON, boardView.getMeasuredWidth() / 60, boardView.getMeasuredHeight() / 60); } catch (IOException e) { this.game.initGame( level, boardView.getMeasuredWidth() / 60, boardView.getMeasuredHeight() / 60); } } else { this.game.initGame( level, boardView.getMeasuredWidth() / 60, boardView.getMeasuredHeight() / 60); } } // am.close(); boardView.setGame(this.game); boardView.invalidate(); boardView.getHowdyShadeView().invalidate(); Toast.makeText(this, this.level + "", Toast.LENGTH_SHORT).show(); Log.i( TAG, "Max tiles : " + (boardView.getMeasuredWidth() / 60) * (boardView.getMeasuredHeight() / 60)); }
protected Boolean doInBackground(ArrayList... params) { download_photos.this.runOnUiThread( new Runnable() { public void run() { mtext.setText( getText(R.string.download_textview_message_1) + " " + path.toString() + ". "); } }); if (resume_file.exists()) { initial_value = readProgress()[0]; } else { initial_value = 1; } for (int i = initial_value - 1; i < links.size(); i++) { // asynctask expects more than one ArrayList<String> item, but we are sending only one, // which is params[0] Uri imageuri = Uri.parse(params[0].get(i).toString()); URL imageurl = null; HttpURLConnection connection = null; total_files_to_download = links.size(); completed_downloads = i + 1; try { imageurl = new URL(params[0].get(i).toString()); connection = (HttpURLConnection) imageurl.openConnection(); connection.connect(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } // extracts the real file name of the photo from url path_segments = imageuri.getPathSegments(); int total_segments = path_segments.size(); file_name = path_segments.get(total_segments - 1); path.mkdirs(); // if(i==0) // first_image = path.toString() + "/" + file_name; InputStream input; OutputStream output; try { input = new BufferedInputStream(imageurl.openStream()); fully_qualified_file_name = new File(path, file_name); output = new BufferedOutputStream(new FileOutputStream(fully_qualified_file_name)); byte data[] = new byte[1024]; int count; while ((count = input.read(data)) != -1) { output.write(data, 0, count); } output.flush(); output.close(); input.close(); connection.disconnect(); new folder_scanner(getApplicationContext(), fully_qualified_file_name); publishProgress(completed_downloads, total_files_to_download); if (this.isCancelled()) { writeProgress(completed_downloads, total_files_to_download); break; } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } // creates required folders and subfolders if they do not exist already // boolean success = path.mkdirs(); // makes request to download photos // DownloadManager.Request request = new DownloadManager.Request(imageuri); // set path for downloads // request.setDestinationInExternalPublicDir(Environment.DIRECTORY_PICTURES,sub_path); // request.setDescription("Downloaded using Facebook Album Downloader"); // DownloadManager dm = (DownloadManager)getSystemService(DOWNLOAD_SERVICE); // download is enqueue in download list. it returns unique id for each download // download_id = dm.enqueue(request); } // returns the unique id. we are not using this id return true; }
@Override protected String[] doInBackground(String... parms) { String[] resultarr = new String[1]; String intentstr = parms[0]; // int count = urls.length; // long totalSize = 0; for (int i = 0; i < count; i++) { totalSize += // Downloader.downloadFile(urls[i]); // publishProgress((int) ((i / (float) count) * 100)); // Escape early if cancel() is called // if (isCancelled()) // break; try { // Connect to API and authenticate publishProgress("Connecting and authenticating API session..."); ApiWrapper wrapper; // wrapper = Api.wrapper; wrapper = new ApiWrapper(Api.mClientID, Api.mClientSecret, null, null); wrapper.login("un1tz3r0", "Farscap3"); publishProgress("Resolving url..."); String resolvedurl = resolveURL(wrapper, intentstr); publishProgress("Getting metadata..."); HttpResponse resp = wrapper.get(Request.to(resolvedurl)); JSONObject jso = Http.getJSON(resp); // resultstr = jso.toString(); if (jso.getString("kind").equals("track")) { if (jso.getBoolean("downloadable")) { publishProgress("Getting download redirect URL..."); String dlrurl = wrapper .getURI( Request.to(jso.getString("download_url")).add("allow_redirect", false), false, false) .toString(); HttpResponse dlrresp = wrapper.get(Request.to(dlrurl)); String dlstr = dlrurl; if (dlrresp.getStatusLine().getStatusCode() == HttpStatus.SC_MOVED_TEMPORARILY) { Header dlloch = dlrresp.getFirstHeader("location"); if ((dlloch == null) || (dlloch.getValue() == null)) throw new RuntimeException("Download url HEAD response has no location header"); dlstr = wrapper.getURI(Request.to(dlloch.getValue()), false, false).toString(); } else if (dlrresp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { dlstr = dlrurl; } else { throw new RuntimeException( "Download url HEAD response has wrong status (" + String.valueOf(dlrresp.getStatusLine().getStatusCode()) + " " + dlrresp.getStatusLine().getReasonPhrase() + ")"); } // String dlstr = Request.to( dlloch.getValue() ).add("CLIENT_ID", // Api.mClientID).toString(); // if(dlresp2.getStatusLine().getStatusCode() != // HttpStatus.SC_MOVED_TEMPORARILY) // throw new RuntimeException("Download redirect url HEAD response has // wrong status: " + dlresp2.getStatusLine().toString()); // Header dlloc2 = dlresp2.getFirstHeader("location"); // if((dlloc2 == null) || (dlloc2.getValue() == null)) // throw new RuntimeException("Download redirect url HEAD response has no // location header"); // resultarr = new String[2]; resultarr[1] = jso.getString("title").replaceAll("[^A-Za-z0-9 -]*", "") + "." + jso.getString("original_format"); resultarr[0] = dlstr; } else { Stream st = wrapper.resolveStreamUrl(jso.getString("stream_url"), true); resultarr = new String[2]; resultarr[1] = jso.getString("title").replaceAll("[^A-Za-z0-9 -]*", "").concat(".mp3"); resultarr[0] = st.streamUrl; } } } catch (JSONException e) { resultarr = new String[1]; resultarr[0] = e.toString(); } catch (IOException e) { resultarr = new String[1]; resultarr[0] = e.toString(); } catch (Exception e) { resultarr = new String[1]; resultarr[0] = e.toString(); } return resultarr; }