@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();
    }
  }
Example #2
0
    @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 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;
    }
  /*
   * 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();
    }
  }
  // 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
 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;
    }