2016-04-27 2 views
3

Я разрабатывал, как сделать программный снимок экрана в андроиде, однако, когда это скриншоты, я получаю панель инструментов и черный экран, а не тот, что на самом деле находится на экране.Скриншот черный в Android

Я также попытался сделать скриншот определенного TextView в пользовательском макете InfoWindow, который я создал для карты google. Но это создает исключение нулевого указателя во второй строке ниже.

TextView v1 = (TextView)findViewById(R.id.tv_code); 
v1.setDrawingCacheEnabled(true); 

Есть в любом случае либо фактически скриншот того, что на экране без установки андроида библиотеки скриншота или скриншот с TextView в пользовательских InfoWindow макета

Это мой метод скриншота:

/** 
* Method to take a screenshot programmatically 
*/ 
private void takeScreenshot(){ 
    try { 
     //TextView I could screenshot instead of the whole screen: 
     //TextView v1 = (TextView)findViewById(R.id.tv_code); 

     View v1 = getWindow().getDecorView().getRootView(); 
     v1.setDrawingCacheEnabled(true); 
     Bitmap bitmap = Bitmap.createBitmap(v1.getDrawingCache()); 
     v1.setDrawingCacheEnabled(false); 


     ByteArrayOutputStream bytes = new ByteArrayOutputStream(); 
     bitmap.compress(Bitmap.CompressFormat.JPEG, 40, bytes); 
     File f = new File(Environment.getExternalStorageDirectory() 
       + File.separator + "test.jpg"); 

     FileOutputStream fo = new FileOutputStream(f); 
     fo.write(bytes.toByteArray()); 
     fo.flush(); 
     fo.close(); 

     MediaStore.Images.Media.insertImage(getContentResolver(), f.getAbsolutePath(), f.getName(), f.getName()); 
     Log.d("debug", "Screenshot saved to gallery"); 

     Toast.makeText(HuntActivity.this,"Code Saved!",Toast.LENGTH_LONG).show(); 

    } catch (FileNotFoundException e) { 
     e.printStackTrace(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
} 

EDIT: Я изменил метод на источник, предоставленный от источника

How can i take/merge screen shot of Google map v2 and layout of xml both programmatically?

Однако это ничего не делает.

public void captureMapScreen() { 
    GoogleMap.SnapshotReadyCallback callback = new GoogleMap.SnapshotReadyCallback() { 

     @Override 
     public void onSnapshotReady(Bitmap snapshot) { 
      try { 
       View mView = getWindow().getDecorView().getRootView(); 
       mView.setDrawingCacheEnabled(true); 
       Bitmap backBitmap = mView.getDrawingCache(); 
       Bitmap bmOverlay = Bitmap.createBitmap(
         backBitmap.getWidth(), backBitmap.getHeight(), 
         backBitmap.getConfig()); 

       Canvas canvas = new Canvas(bmOverlay); 
       canvas.drawBitmap(backBitmap, 0, 0, null); 
       canvas.drawBitmap(snapshot, new Matrix(), null); 

       FileOutputStream out = new FileOutputStream(
         Environment.getExternalStorageDirectory() 
           + "/" 
           + System.currentTimeMillis() + ".jpg"); 

       bmOverlay.compress(Bitmap.CompressFormat.JPEG, 90, out); 
      } catch (Exception e) { 
       e.printStackTrace(); 
      } 
     } 
    }; 
    mMap.snapshot(callback); 
} 
+1

Это то, что вы хотите? [Ссылка] (http://stackoverflow.com/questions/18309625/how-can-i-take-merge-screen-shot-of-google-map-v2-and-layout-of-xml-both-program) – calvinfly

+0

Проверьте свои права доступа, если вы включили Lampard

+0

@CrazyAndroid, который уже был в манифесте – user3586417

ответ

1

Я понял это!

/** 
* Method to take a screenshot programmatically 
*/ 
private void takeScreenshot(){ 
    GoogleMap.SnapshotReadyCallback callback = new GoogleMap.SnapshotReadyCallback() { 
     @Override 
     public void onSnapshotReady(Bitmap bitmap) { 
      Bitmap b = bitmap; 
      String timeStamp = new SimpleDateFormat(
        "yyyyMMdd_HHmmss", Locale.getDefault()) 
        .format(new java.util.Date()); 

      String filepath = timeStamp + ".jpg"; 

      try{ 
       OutputStream fout = null; 
       fout = openFileOutput(filepath,MODE_WORLD_READABLE); 
       bitmap.compress(Bitmap.CompressFormat.JPEG, 90, fout); 
       fout.flush(); 
       fout.close(); 
      } catch (FileNotFoundException e) { 
       e.printStackTrace(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
      saveImage(filepath); 
     } 
    }; 
    mMap.snapshot(callback); 
} 

/** 
* Method to save the screenshot image 
* @param filePath the file path 
*/ 
public void saveImage(String filePath) 
{ 
    File file = this.getFileStreamPath(filePath); 

    if(!filePath.equals("")) 
    { 
     final ContentValues values = new ContentValues(2); 
     values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg"); 
     values.put(MediaStore.Images.Media.DATA, file.getAbsolutePath()); 
     final Uri contentUriFile = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values); 
     Toast.makeText(HuntActivity.this,"Code Saved to files!",Toast.LENGTH_LONG).show(); 
    } 
    else 
    { 
     System.out.println("ERROR"); 
    } 
} 

Я адаптировал код по этой ссылке, чтобы он не делился и вместо этого просто сохраняет изображение.

Capture screen shot of GoogleMap Android API V2

Спасибо за всякие помочь

0

Пожалуйста, попробуйте код ниже:

private void takeScreenshot(){ 
    try { 
     //TextView I could screenshot instead of the whole screen: 
     //TextView v1 = (TextView)findViewById(R.id.tv_code); 
     Bitmap bitmap = null; 
     Bitmap bitmap1 = null; 
     View v1 = getWindow().getDecorView().getRootView(); 
     v1.setDrawingCacheEnabled(true); 
     bitmap = Bitmap.createBitmap(v1.getDrawingCache()); 
     try { 
     if (bitmap != null) 
      bitmap1 = Bitmap.createBitmap(bitmap, 0, 0, 
        v1.getWidth(), v1.getHeight()); 
     } catch (OutOfMemoryError e) { 
      e.printStackTrace(); 
     } 
     v1.setDrawingCacheEnabled(false); 


     ByteArrayOutputStream bytes = new ByteArrayOutputStream(); 
     bitmap1.compress(Bitmap.CompressFormat.JPEG, 40, bytes); 
     File f = new File(Environment.getExternalStorageDirectory() 
       + File.separator + "test.jpg"); 

     FileOutputStream fo = new FileOutputStream(f); 
     fo.write(bytes.toByteArray()); 
     fo.flush(); 
     fo.close(); 

     MediaStore.Images.Media.insertImage(getContentResolver(), f.getAbsolutePath(), f.getName(), f.getName()); 
     Log.d("debug", "Screenshot saved to gallery"); 

     Toast.makeText(HuntActivity.this,"Code Saved!",Toast.LENGTH_LONG).show(); 

    } catch (FileNotFoundException e) { 
     e.printStackTrace(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
} 
+0

Для меня это все еще производит черный снимок экрана. Это монитор Android, когда снимок сделан. http: // pastebin.com/Tx5q9AHV – user3586417

0

Используйте этого код

private void takeScreenshot() { 
    AsyncTask<Void, Void, Void> asyc = new AsyncTask<Void, Void, Void>() { 
     @Override 
     protected void onPreExecute() { 
      super.onPreExecute(); 
      objUsefullData.showProgress("Please wait", ""); 

     } 

     @Override 
     protected Void doInBackground(Void... params) { 
      try { 
       // create bitmap screen capture 
       View v1 = getWindow().getDecorView().getRootView(); 
       v1.setDrawingCacheEnabled(true); 
       bitmapscreen_shot = Bitmap.createBitmap(v1 
         .getDrawingCache()); 
       v1.setDrawingCacheEnabled(false); 
       String state = Environment.getExternalStorageState(); 
       File folder = null; 
       if (state.contains(Environment.MEDIA_MOUNTED)) { 
        folder = new File(
          Environment.getExternalStorageDirectory() 
            + "/piccapella"); 
       } else { 
        folder = new File(
          Environment.getExternalStorageDirectory() 
            + "/piccapella"); 
       } 
       boolean success = true; 
       if (!folder.exists()) { 
        success = folder.mkdirs(); 
       } 
       if (success) { 
        // Create a media file name 
        String timeStamp = new SimpleDateFormat(
          "yyyyMMdd_HHmmss", Locale.getDefault()) 
          .format(new java.util.Date()); 
        imageFile = new File(folder.getAbsolutePath() 
          + File.separator + "IMG_" + timeStamp + ".jpg"); 
        /* 
        * Toast.makeText(AddTextActivity.this, 
        * "saved Image path" + "" + imageFile, 
        * Toast.LENGTH_SHORT) .show(); 
        */ 
        imageFile.createNewFile(); 
       } else { 
        /* 
        * Toast.makeText(AddTextActivity.this, 
        * "Image Not saved", Toast.LENGTH_SHORT).show(); 
        */ 
       } 
       ByteArrayOutputStream ostream = new ByteArrayOutputStream(); 
       // save image into gallery 
       bitmapscreen_shot.compress(CompressFormat.JPEG, 100, 
         ostream); 
       FileOutputStream fout = new FileOutputStream(imageFile); 
       fout.write(ostream.toByteArray()); 
       fout.close(); 
       Log.e("image_screen_shot", "" + imageFile); 
      } catch (Throwable e) { 
       // Several error may come out with file handling or OOM 
       e.printStackTrace(); 
      } 
      return null; 
     } 

     @Override 
     protected void onPostExecute(Void result) { 
      // TODO Auto-generated method stub 
      super.onPostExecute(result); 
      objUsefullData.dismissProgress(); 

     } 
    }; 
    asyc.execute(); 
} 

Надеется, что это поможет вам

+0

С этим говорит, что «Метод getRootView должен быть вызван из потока пользовательского интерфейса, в настоящее время установленный поток является рабочим» в этих строках: Просмотреть v1 = getWindow(). getDecorView(). getRootView(); v1.setDrawingCacheEnabled (true); Bitmap bitmapscreen_shot = Bitmap.createBitmap (v1 .getDrawingCache()); v1.setDrawingCacheEnabled (false); – user3586417

+0

да, но в моем конце его рабочий тон, я получаю идеальный снимок экрана с хорошим качеством – sukhbir

0

Я столкнулся с этой проблемой. После v1.setDrawingCacheEnabled (true); Я добавил:

v1.buildDrawingCache();

И положил задержку на вызов takeScreenshot(); метод.

Устранено.

Смежные вопросы