I wanted to make my app be able to take proper screenshots like my own device does on touch of a button but it appears that it just takes screenshot of the view. What I want is to be able to take full screenshots with whatever it is on the screen like my device does.
Here's my java code:
package com.arvisapps.lazyscreenshot;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
public class MainActivity extends Activity {
RelativeLayout R1;
ImageView img;
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
private void showNotification() {
builder.setAutoCancel(false);
builder.setContentTitle("Take Screenshot");
builder.setContentText("");
builder.setSmallIcon(R.drawable.ic_notification);
builder.setOngoing(true);
Notification notification = builder.build();
NotificationManager manager = (NotificationManager) this.getSystemService(NOTIFICATION_SERVICE);
manager.notify(1, notification);
}
private void dontShowNotification(){
NotificationManager nMgr = (NotificationManager) this.getSystemService(NOTIFICATION_SERVICE);
nMgr.cancel(1);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
R1 = (RelativeLayout) findViewById(R.id.relatv);
CheckBox cb1 = (CheckBox) findViewById(R.id.cb_1);
cb1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked == true) {
showNotification();
} else if (isChecked == false) {
dontShowNotification();
}
}
});
}
public void takeScreenshot(View v)
{
View v1 = R1.getRootView();
v1.setDrawingCacheEnabled(true);
Bitmap bm = v1.getDrawingCache();
BitmapDrawable bmDrawable = new BitmapDrawable(bm);
img = (ImageView) findViewById(R.id.screenshots);
img.setBackgroundDrawable(bmDrawable);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Here's my XML:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/relatv"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity">
<RelativeLayout
android:id="#+id/cb1_grp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true">
<TextView
android:id="#+id/cb1_txtvw"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="15dp"
android:text="#string/cb1_txt" />
<CheckBox
android:id="#+id/cb_1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#id/cb1_txtvw"
android:layout_marginLeft="107dp"
android:layout_marginStart="107dp"/>
</RelativeLayout>
<LinearLayout
android:id="#+id/edittxt_grp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/cb1_grp"
android:layout_centerHorizontal="true">
<TextView
android:id="#+id/edittxt_txtvw"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/delaytime" />
<EditText
android:id="#+id/edittxt_delay"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"/>
</LinearLayout>
<Button
android:id="#+id/btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/edittxt_grp"
android:layout_centerHorizontal="true"
android:text="#string/btn1_txt"
android:onClick="takeScreenshot"/>
<ImageView
android:layout_below="#id/btn1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/screenshots"
android:contentDescription="#string/app_name"
/>
If your phone is rooted try.
Process sh = Runtime.getRuntime().exec("su", null,null);
OutputStream os = sh.getOutputStream();
os.write(("/system/bin/screencap -p " + "/sdcard/img.png").getBytes("ASCII"));
os.flush();
os.close();
sh.waitFor();
then read img.png as bitmap and convert it jpg as follows
Bitmap screen = BitmapFactory.decodeFile(Environment.getExternalStorageDirectory()+
File.separator +"img.png");
//my code for saving
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
screen.compress(Bitmap.CompressFormat.JPEG, 15, bytes);
//you can create a new file name "test.jpg" in sdcard folder.
File f = new File(Environment.getExternalStorageDirectory()+ File.separator + "test.jpg");
f.createNewFile();
//write the bytes in file
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
// remember close de FileOutput
fo.close();
The method you're using, getDrawingCache() will only get that view's drawing cache. Unfortunately, an application cannot directly access the framebuffer (and thus the raw pixels) unless your device is rooted so you won't be able to take a full screenshot from your app.
Related
Here's the code I'm using to render a PDF called "answerkey.pdf" that's stored in "Download/Adobe Reader/answerkey.pdf"
package com.practice.pdftest;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.Rect;
import android.graphics.pdf.PdfRenderer;
import android.os.Environment;
import android.os.ParcelFileDescriptor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
public class MainActivity extends Activity {
private ImageView imageView;
private Button next, previous;
private TextView tv;
private int currentPage = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
next = (Button)findViewById(R.id.next);
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
currentPage++;
render();
}
});
previous = (Button)findViewById(R.id.previous);
previous.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
currentPage--;
render();
}
});
// tv = (TextView)findViewById(R.id.testText);
// tv.setText(Environment.getExternalStorageDirectory().getAbsolutePath());
//
// Toast toast = Toast.makeText(getApplicationContext(),Environment.getExternalStorageDirectory().getAbsolutePath(),Toast.LENGTH_LONG);
// toast.show();
}
private void render() {
try {
imageView = (ImageView)findViewById(R.id.imageView);
int REQ_WIDTH = 1;
int REQ_HEIGHT = 1;
REQ_WIDTH = imageView.getWidth();
REQ_HEIGHT = imageView.getHeight();
Bitmap bitmap = Bitmap.createBitmap(REQ_WIDTH, REQ_HEIGHT, Bitmap.Config.ARGB_4444);
File file = new File(Environment.getDataDirectory().getPath()+"Adobe Reader/answerkey.pdf");
PdfRenderer pdfRenderer = new PdfRenderer(ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY));
if(currentPage < 0) {
currentPage=0;
}
else if (currentPage > pdfRenderer.getPageCount()) {
currentPage = pdfRenderer.getPageCount()-1;
}
Matrix matrix = imageView.getImageMatrix();
Rect rect = new Rect(0,0,REQ_HEIGHT,REQ_WIDTH);
pdfRenderer.openPage(currentPage).render(bitmap,rect,matrix,PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY);
imageView.setImageMatrix(matrix);
imageView.setImageBitmap(bitmap);
imageView.invalidate();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Here's the layout.xml file I've made -
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:orientation="vertical"
tools:context="com.practice.pdftest.MainActivity">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/imageView"
android:layout_weight="4"
android:background="#android:color/white"
android:layout_marginBottom="20dp"
/>
<!--<TextView-->
<!--android:layout_width="wrap_content"-->
<!--android:layout_height="wrap_content"-->
<!--android:id="#+id/testText"-->
<!--android:text="Test"-->
<!--/>-->
<LinearLayout
android:layout_width="match_parent"
android:orientation="horizontal"
android:layout_weight="2"
android:gravity="center"
android:layout_height="wrap_content"
android:layout_marginTop="-100dp">
<Button
android:id="#+id/previous"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:text="Previous"
/>
<Button
android:id="#+id/next"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:text="Next" />
</LinearLayout>
</LinearLayout>
For some reason, the PDF just isn't being displayed on screen, I keep getting a white, blank background. What am I doing wrong? Is the path incorrect? I have no SD card on my device. Or am I doing something wrong with the bitmap?
Is the path incorrect?
Yes.
I have no SD card on my device
That is fine. That would be removable storage. I am interpreting "Download/Adobe Reader/answerkey.pdf" as referring to something on external storage.
The recommended way to get this location would be to replace:
File file = new File(Environment.getDataDirectory().getPath()+"Adobe Reader/answerkey.pdf");
with:
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "Adobe Reader/answerkey.pdf");
Note that your app will need to request the READ_EXTERNAL_STORAGE or WRITE_EXTERNAL_STORAGE permission, and that will involve runtime permissions on Android 6.0+ (if your targetSdkVersion is 23 or higher).
ERROR LINE:java.lang.NullPointerException: Attempt to invoke virtual
method 'void android.widget.ImageView.setOnClickListener(android.view.View$OnClickListener)'
on a null object reference
.JAVA FILE
package co.hangyr.Hangyr.Activity.Camera;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.hardware.Camera;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import butterknife.ButterKnife;
import butterknife.InjectView;
import co.hangyr.Hangyr.Activity.Home.ActivityHome;
import co.hangyr.Hangyr.Activity.Others.Footer;
import co.hangyr.Hangyr.R;
public class ActivityCamera extends Footer implements View.OnClickListener {
static final int RESULT_LOAD_IMAGE = 1;
private Camera mCamera;
private CameraPreview mCameraPreview;
ImageView imageView;
/* static final int SECOND_PIC = 2;
static final int THIRD_PIC = 3;
static final int FORTH_PIC = 4;
static final int FIFTH_PIC = 5;
*/
#InjectView(R.id.ivFirstPic)
ImageView firstPic;
#InjectView(R.id.ivCapture)
ImageView ivCapture;
#InjectView(R.id.ivFlipCamera)
ImageView flipCamera;
#InjectView(R.id.ivFlash)
ImageView flash;
#InjectView(R.id.tvUploadFromGallery)
TextView tvUploadFromGallery;
#InjectView(R.id.ivSecondPic)
ImageView secondPic;
#InjectView(R.id.ivThirdPic)
ImageView thirdPic;
#InjectView(R.id.ivForthPic)
ImageView forthPic;
#InjectView(R.id.ivFifthPic)
ImageView fifthPic;
#InjectView(R.id.ivJustClicked)
FrameLayout justClicked;
// #InjectView(R.id.tvNextEditPic)
TextView tvNext;
#InjectView(R.id.bDeleteFirstPic)
Button deleteFirstPic;
#InjectView(R.id.bDeleteSecondPic)
Button deleteSecondPic;
#InjectView(R.id.bDeleteThirdPic)
Button deleteThirdPic;
#InjectView(R.id.bDeleteForthPic)
Button deleteForthPic;
#InjectView(R.id.bDeleteFifthPic)
Button deleteFifthPic;
#InjectView(R.id.tvCancel)
TextView tvCancel;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.camera);
ButterKnife.inject(this);
tvNext = (TextView) findViewById(R.id.tvNextEditPic);
tvNext.setOnClickListener(this);
mCamera = getCameraInstance();
mCamera.setDisplayOrientation(90);
mCameraPreview = new CameraPreview(this, mCamera);
justClicked.addView(mCameraPreview);
ivCapture.setOnClickListener(this);
tvUploadFromGallery.setOnClickListener(this);
firstPic.setOnClickListener(this);
deleteFirstPic.setOnClickListener(this);
deleteSecondPic.setOnClickListener(this);
deleteThirdPic.setOnClickListener(this);
deleteForthPic.setOnClickListener(this);
deleteFifthPic.setOnClickListener(this);
tvCancel.setOnClickListener(this);
}
private Camera getCameraInstance() {
Camera camera = null;
try {
camera = Camera.open();
flipCamera.setVisibility(View.VISIBLE);
flash.setVisibility(View.VISIBLE);
} catch (Exception e) {
// cannot get camera or does not exist
}
return camera;
}
Camera.PictureCallback mPicture = new Camera.PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
File pictureFile = getOutputMediaFile();
if (pictureFile == null) {
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
Bitmap bmp = BitmapFactory.decodeByteArray(data, 0, data.length);
firstPic.setImageBitmap(bmp);
fos.write(data);
fos.close();
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
}
};
private static File getOutputMediaFile() {
File mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
"MyCameraApp");
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d("MyCameraApp", "failed to create directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
.format(new Date());
File mediaFile;
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "IMG_" + timeStamp + ".jpg");
return mediaFile;
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.ivCapture:
mCamera.takePicture(null, null, mPicture);
break;
case R.id.ivFirstPic:
mCameraPreview.getHolder().removeCallback(mCameraPreview);
Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
deleteFirstPic.setVisibility(View.VISIBLE);
break;
case R.id.tvCancel:
startActivity(new Intent(getApplicationContext(), ActivityHome.class));
break;
case R.id.tvNextEditPic:
startActivity(new Intent(getApplicationContext(), UploadPic.class));
break;
case R.id.bDeleteFirstPic:
firstPic.setImageResource(R.drawable.pic_item_cam);
deleteFirstPic.setVisibility(View.GONE);
break;
case R.id.bDeleteSecondPic:
secondPic.setImageResource(R.drawable.pic_item_cam);
deleteSecondPic.setVisibility(View.GONE);
break;
case R.id.bDeleteThirdPic:
thirdPic.setImageResource(R.drawable.pic_item_cam);
deleteThirdPic.setVisibility(View.GONE);
break;
case R.id.bDeleteForthPic:
forthPic.setImageResource(R.drawable.pic_item_cam);
deleteForthPic.setVisibility(View.GONE);
break;
case R.id.bDeleteFifthPic:
fifthPic.setImageResource(R.drawable.pic_item_cam);
deleteFifthPic.setVisibility(View.GONE);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
firstPic.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
}
}
.XML FILE
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/backgroundApp"
android:orientation="vertical"
android:weightSum="2">
<LinearLayout
android:id="#+id/llNameBack"
android:layout_width="match_parent"
android:layout_height="48dp"
android:layout_marginBottom="1dp"
android:background="#color/white"
android:orientation="horizontal"
android:weightSum="2">
<TextView
android:id="#+id/tvCancel"
android:layout_width="match_parent"
android:layout_height="48dp"
android:layout_gravity="left|center"
android:layout_marginBottom="15dp"
android:paddingLeft="15dp"
android:layout_marginTop="14dp"
android:layout_weight="1"
android:gravity="left|center_vertical"
android:text="#string/cancelS"
android:textColor="#color/black"
android:textSize="13dp"
android:textStyle="bold" />
<TextView
android:id="#+id/tvNextEditPic"
android:layout_width="match_parent"
android:layout_height="48dp"
android:layout_gravity="end|center_vertical"
android:layout_marginBottom="15dp"
android:paddingRight="15dp"
android:layout_marginTop="14dp"
android:layout_weight="1"
android:background="#color/white"
android:gravity="right|center_vertical"
android:text="#string/nextS"
android:textColor="#fd676a"
android:textSize="13dp"
android:textStyle="bold" />
</LinearLayout>
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="375dp">
<FrameLayout
android:id="#+id/ivJustClicked"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center_horizontal"
android:layout_margin="5dp"
android:layout_weight="1">
<ImageView
android:id="#+id/ivFlipCamera"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="left|bottom"
android:padding="8dp"
android:src="#drawable/flip_camera" />
<ImageView
android:id="#+id/ivFlash"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right|bottom"
android:padding="8dp"
android:src="#drawable/flash_icon" />
</FrameLayout>
</RelativeLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/white"
android:orientation="vertical">
<TextView
android:id="#+id/tvUploadFromGallery"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#color/white"
android:padding="18dp"
android:text="#string/galleryS"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#4a4a4a"
android:textSize="13dp"
android:textStyle="bold" />
<ImageView
android:id="#+id/ivCapture"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginBottom="16dp"
android:layout_marginTop="-30dp"
android:src="#drawable/capture" />
<include
layout="#layout/camera_pic_added"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginTop="1dp"
android:layout_weight="1" />
</LinearLayout>
</LinearLayout>
</ScrollView>
</LinearLayout>
You should use #Bindinstead of #InjectView
#InjectView was replaced June 2015.
You missed to initialize this variable ivFirstPic:
ivFirstPic.setOnClickListener(this);
I put Signatureview inside Android Scrollview.
But while writing something on SignatureView, scrolling up and down I'm not able to write my sign.
How to Disable the Scrollview when SignatureView is touched
Link to referred signature
Sign.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
>
<ScrollView
android:id="#+id/scrollView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:isScrollContainer="false"
android:paddingBottom="30dp"
android:paddingLeft="2dp"
android:paddingRight="2dp"
android:scrollbars="none">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<com.kyanogen.signatureview.SignatureView
xmlns:sign="http://schemas.android.com/apk/res-auto"
android:id="#+id/signature_view"
android:layout_width="match_parent"
android:layout_height="100dp"
android:minHeight="250dp"
android:layout_weight="1"
sign:penSize="5dp"
sign:backgroundColor="#ffffff"
sign:penColor="#000000"
sign:enableSignature="true"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:weightSum="2">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/clearSignButton"
android:layout_weight="1"
android:text="clear"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/saveSignButton"
android:layout_weight="1"
android:text="save"/>
</LinearLayout>
</LinearLayout>
</LinearLayout>
</Scrolview>
Main.java
package com.example.parsaniahardik.signaturedemo;
import android.graphics.Bitmap;
import android.media.MediaScannerConnection;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import com.kyanogen.signatureview.SignatureView;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Calendar;
public class MainActivity extends AppCompatActivity {
Bitmap bitmap;
Button clear,save;
SignatureView signatureView;
String path;
private static final String IMAGE_DIRECTORY = "/signdemo";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
signatureView = (SignatureView) findViewById(R.id.signature_view);
clear = (Button) findViewById(R.id.clear);
save = (Button) findViewById(R.id.save);
clear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
signatureView.clearCanvas();
}
});
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
bitmap = signatureView.getSignatureBitmap();
path = saveImage(bitmap);
}
});
}
public String saveImage(Bitmap myBitmap) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
myBitmap.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
File wallpaperDirectory = new File(
Environment.getExternalStorageDirectory() + IMAGE_DIRECTORY /*iDyme folder*/);
// have the object build the directory structure, if needed.
if (!wallpaperDirectory.exists()) {
wallpaperDirectory.mkdirs();
Log.d("hhhhh",wallpaperDirectory.toString());
}
try {
File f = new File(wallpaperDirectory, Calendar.getInstance()
.getTimeInMillis() + ".jpg");
f.createNewFile();
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
MediaScannerConnection.scanFile(MainActivity.this,
new String[]{f.getPath()},
new String[]{"image/jpeg"}, null);
fo.close();
Log.d("TAG", "File Saved::--->" + f.getAbsolutePath());
return f.getAbsolutePath();
} catch (IOException e1) {
e1.printStackTrace();
}
return "";
}
}
when you want to sign you need to intercept the scroll event when the signature is touched. and when you are outside of the signature area turn back the normal status: the scrollView intercept the scroll event.
inside onCreate in your controller add the following :
signatureView.setOnTouchListener(new View.OnTouchListener(){
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
int action = motionEvent.getAction();
switch (action){
case MotionEvent.ACTION_DOWN:
// Disable the scroll view to intercept the touch event
scrollView1.requestDisallowInterceptTouchEvent(true);
return false;
case MotionEvent.ACTION_UP:
// Allow scroll View to interceot the touch event
scrollView1.requestDisallowInterceptTouchEvent(false);
return true;
case MotionEvent.ACTION_MOVE:
scrollView1.requestDisallowInterceptTouchEvent(true);
return false;
default:
return true;
}
}
});
You have to intercept touch events in this SignatureView. The best approach is to subclass it and override onTouchEvent:
public class MySignatureView extends SignatureView {
#Override
public boolean onTouchEvent(MotionEvent event) {
// intercept touch event here, so it's not passed to ScrollView
super.onTouchEvent(event);
return false;
}
}
And then, of course change SignatureView to MySignatureView in your layout.
<com.your.package.name.MySignatureView
xmlns:sign="http://schemas.android.com/apk/res-auto"
android:id="#+id/signature_view"
android:layout_width="match_parent"
android:layout_height="100dp"
android:minHeight="250dp"
android:layout_weight="1"
sign:penSize="5dp"
sign:backgroundColor="#ffffff"
sign:penColor="#000000"
sign:enableSignature="true"/>
That is my code java
intent.putExtra(Intent.EXTRA_SUBJECT, "My App name and some text");
intent.putExtra(Intent.EXTRA_TEXT, "a link");
intent.putExtra(Intent.EXTRA_STREAM,getImageUri(context,mBitmap));
intent.setType("image/*,text/plain");
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
I want to share image and text. This code works on WhatsApp, Twitter, Gmail , etc .. but it does not work on Facebook
thank you in advance for your help
If you want to share the Image and text on Facebook without using Facebook SDK then you have to create the bitmap of your image plus text and then you can share that bitmap on facebook.
Download the source code from here (Share image and text on facebook using intent in android)
activity_main.xml
<RelativeLayout android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff"
xmlns:android="http://schemas.android.com/apk/res/android">
<EditText
android:id="#+id/et_text"
android:layout_width="match_parent"
android:textSize="15dp"
android:layout_height="45dp"
android:layout_marginTop="10dp"
android:background="#drawable/edittext_drawable"
android:hint="Enter your text"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:paddingRight="10dp"
android:inputType="text"
android:imeOptions="actionDone"
android:paddingLeft="10dp"
android:singleLine="true"
android:textColorHint="#979797" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/rl_main"
android:background="#ffffff"
android:layout_below="#+id/et_text"
android:layout_above="#+id/tv_share">
<ImageView
android:layout_width="match_parent"
android:layout_height="250dp"
android:src="#drawable/index"
android:scaleType="fitXY"
android:id="#+id/iv_image"
android:layout_marginTop="10dp"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="15dp"
android:id="#+id/tv_text"
android:layout_below="#+id/iv_image"
android:layout_margin="10dp"
android:textColor="#000000"
android:maxLines="5"
/>
</RelativeLayout>
<TextView
android:id="#+id/tv_share"
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#F38D0A"
android:gravity="center"
android:padding="10dp"
android:layout_margin="10dp"
android:text="Share"
android:textColor="#ffffff"
android:textSize="15dp"
android:layout_alignParentBottom="true"/>
</RelativeLayout>
MainActivity.java
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
EditText et_text;
ImageView iv_image;
TextView tv_share,tv_text;
RelativeLayout rl_main;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
}
private void init(){
et_text = (EditText)findViewById(R.id.et_text);
iv_image = (ImageView)findViewById(R.id.iv_image);
tv_share = (TextView)findViewById(R.id.tv_share);
rl_main = (RelativeLayout)findViewById(R.id.rl_main);
tv_text= (TextView) findViewById(R.id.tv_text);
File dir = new File("/sdcard/Testing/");
try {
if (dir.mkdir()) {
System.out.println("Directory created");
} else {
System.out.println("Directory is not created");
}
} catch (Exception e) {
e.printStackTrace();
}
tv_share.setOnClickListener(this);
et_text.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
tv_text.setText(et_text.getText().toString());
}
});
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.tv_share:
Bitmap bitmap1 = loadBitmapFromView(rl_main, rl_main.getWidth(), rl_main.getHeight());
saveBitmap(bitmap1);
String str_screenshot = "/sdcard/Testing/"+"testing" + ".jpg";
fn_share(str_screenshot);
break;
}
}
public void saveBitmap(Bitmap bitmap) {
File imagePath = new File("/sdcard/Testing/"+"testing" + ".jpg");
FileOutputStream fos;
try {
fos = new FileOutputStream(imagePath);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.flush();
fos.close();
Log.e("ImageSave", "Saveimage");
} catch (FileNotFoundException e) {
Log.e("GREC", e.getMessage(), e);
} catch (IOException e) {
Log.e("GREC", e.getMessage(), e);
}
}
public static Bitmap loadBitmapFromView(View v, int width, int height) {
Bitmap b = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
v.draw(c);
return b;
}
public void fn_share(String path) {
File file = new File("/mnt/" + path);
Bitmap bmp = BitmapFactory.decodeFile(file.getAbsolutePath());
Uri uri = Uri.fromFile(file);
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("image/*");
intent.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(intent, "Share Image"));
}
}
Thanks!
You can share int value of an image as R.drawable.image and get it with getResources.getDrawable(int)
I am new to android and i am making an application which is take information from visitor's and make a pdf from it and save it internal storage,it also have the option for printing the information via printers connected through wifi
Here is my main java file Visitor_pass -
package com.example.sayedshazeb.practical1;
import android.annotation.TargetApi;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.nfc.Tag;
import android.print.PrintManager;
import android.provider.MediaStore;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.app.ActionBar;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.os.Build;
import android.os.CancellationSignal;
import android.os.ParcelFileDescriptor;
import android.print.PageRange;
import android.print.PrintAttributes;
import android.print.PrintDocumentAdapter;
import android.content.Context;
import android.print.PrintDocumentInfo;
import android.print.pdf.PrintedPdfDocument;
import android.graphics.pdf.PdfDocument;
import android.widget.TextView;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URI;
public class Visitor_pass extends ActionBarActivity implements ImageAndTextContainer {
ImageView iv;
public Context c;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_visitor_pass);
iv = (ImageView) findViewById(R.id.image);
Button cbtn = (Button)findViewById(R.id.captureimage);
cbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent,0);
}
});
Button pbtn = (Button) findViewById(R.id.print);
pbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
printDocument(v);
}
});
Button s =(Button)findViewById(R.id.Dbsave);
s.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Bitmap bm = (Bitmap) data.getExtras().get("data");
iv.setImageBitmap(bm);
}
#TargetApi(Build.VERSION_CODES.KITKAT)
public void printDocument(View view)
{
// Get a PrintManager instance
PrintManager printManager = (PrintManager) this.getSystemService(Context.PRINT_SERVICE);
// Give the job a name.
String jobName = this.getString(R.string.app_name) +
" Document";
// Start a print job, passing a printDocumentAdapter as
//argument to handle the generation of a print document
MyPrintDocumentAdapter printDoc = new MyPrintDocumentAdapter(this);
printManager.print(jobName, printDoc, null);
}
#Override
public Bitmap getImage() {
ImageView imageView = (ImageView) findViewById(R.id.image);
Bitmap image = null;
// Get the image
if ((imageView.getDrawable()) != null) {
// Send it to the print helper
image = ((BitmapDrawable) imageView.getDrawable()).getBitmap();
}
return image;
}
#TargetApi(Build.VERSION_CODES.KITKAT)
public class MyPrintDocumentAdapter extends PrintDocumentAdapter
{
private ImageAndTextContainer imageAndTextContainer;
Context context;
private int pageHeight;
private int pageWidth;
public PdfDocument myPdfDocument;
public int totalpages = 1;
String pts;
String ats;
String cts;
public MyPrintDocumentAdapter(ImageAndTextContainer container) {
this.context =context;
this.imageAndTextContainer = container;
}
#TargetApi(Build.VERSION_CODES.KITKAT)
#Override
public void onLayout(PrintAttributes oldAttributes, PrintAttributes newAttributes, CancellationSignal cancellationSignal, LayoutResultCallback callback, Bundle extras) {
myPdfDocument = new PrintedPdfDocument(context, newAttributes);
pageHeight =
newAttributes.getMediaSize().getHeightMils()/1000 * 72;
pageWidth =
newAttributes.getMediaSize().getWidthMils()/1000 * 72;
if (cancellationSignal.isCanceled() ) {
callback.onLayoutCancelled();
return;
}
if (totalpages > 0) {
PrintDocumentInfo.Builder builder = new PrintDocumentInfo
.Builder("print_output.pdf")
.setContentType(PrintDocumentInfo.CONTENT_TYPE_DOCUMENT)
.setPageCount(totalpages);
PrintDocumentInfo info = builder.build();
callback.onLayoutFinished(info, true);
} else {
callback.onLayoutFailed("Page count is zero.");
}
}
#Override
public void onWrite(PageRange[] pages, ParcelFileDescriptor destination, CancellationSignal cancellationSignal, WriteResultCallback callback) {
for (int i = 0; i < totalpages; i++) {
if (pageInRange(pages, i))
{
PdfDocument.PageInfo newPage = new PdfDocument.PageInfo.Builder(pageWidth,
pageHeight, i).create();
PdfDocument.Page page =
myPdfDocument.startPage(newPage);
if (cancellationSignal.isCanceled()) {
callback.onWriteCancelled();
myPdfDocument.close();
myPdfDocument = null;
return;
}
drawPage(page, i);
myPdfDocument.finishPage(page);
}
}
try {
myPdfDocument.writeTo(new FileOutputStream(
destination.getFileDescriptor()));
} catch (IOException e) {
callback.onWriteFailed(e.toString());
return;
} finally {
myPdfDocument.close();
myPdfDocument = null;
}
callback.onWriteFinished(pages);
}
private boolean pageInRange(PageRange[] pageRanges, int page)
{
for (int i = 0; i<pageRanges.length; i++)
{
if ((page >= pageRanges[i].getStart()) &&
(page <= pageRanges[i].getEnd()))
return true;
}
return false;
}
private void drawPage(PdfDocument.Page page,
int pagenumber) {
Canvas canvas = page.getCanvas();
pagenumber++; // Make sure page numbers start at 1
int titleBaseLine = 72;
int leftMargin = 54;
EditText pt = (EditText)findViewById(R.id.textname);
EditText ct = (EditText)findViewById(R.id.textphone);
pts = pt.getText().toString();
EditText at = (EditText)findViewById(R.id.textaddress);
ats = at.getText().toString();
cts = ct.getText().toString();
DatePicker datePicker = (DatePicker) findViewById(R.id.datePicker);
int day = datePicker.getDayOfMonth();
String d = ""+day;
int month = datePicker.getMonth() + 1;
String m = ""+month;
int year = datePicker.getYear();
String y=""+year;
Paint paint = new Paint();
paint.setColor(Color.BLACK);
paint.setTextSize(40);
canvas.drawText("Visitor Details " + pagenumber, leftMargin, titleBaseLine, paint);
paint.setTextSize(25);
canvas.drawText("Name :", leftMargin, titleBaseLine + 400, paint);
canvas.drawText(pts ,leftMargin + 110,titleBaseLine + 400,paint);
canvas.drawText("Address :",leftMargin,titleBaseLine + 450,paint);
canvas.drawText(ats ,leftMargin + 110,titleBaseLine + 450,paint);
canvas.drawText("Number :",leftMargin,titleBaseLine + 500,paint);
canvas.drawText(cts ,leftMargin + 110,titleBaseLine + 500,paint);
canvas.drawText("Date :" ,leftMargin,titleBaseLine + 550,paint);
canvas.drawText( d + "/" +m+"/"+y ,leftMargin+110,titleBaseLine + 550,paint);
Rect imageRect = new Rect(100, 100, canvas.getWidth() - 240, canvas.getHeight() / 2 - 10);
drawImage(imageAndTextContainer.getImage(), canvas, imageRect);
}
private void drawImage(Bitmap image, Canvas canvas, Rect r) {
canvas.drawBitmap(image, null, r, new Paint());
}
}
}
And Here is my main Xml file-
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".Visitor_pass"
android:orientation="vertical"
android:weightSum="1">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Visitor's Pass"
android:id="#+id/visitorpass"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_gravity="center"
android:textSize="20dp" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:ems="10"
android:id="#+id/textname"
android:layout_gravity="center"
android:layout_marginTop="15dp"
android:hint="Enter visitor's name"
android:focusableInTouchMode="true" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPostalAddress"
android:ems="10"
android:id="#+id/textaddress"
android:layout_gravity="center"
android:layout_marginTop="15dp"
android:hint="Enter Address"
android:focusableInTouchMode="true" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="phone"
android:ems="10"
android:id="#+id/textphone"
android:layout_gravity="center"
android:layout_marginTop="15dp"
android:focusableInTouchMode="true"
android:hint="Enter Number" />
<DatePicker
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/datePicker"
android:layout_gravity="center_horizontal"
android:calendarViewShown="false"
android:datePickerMode="spinner" />
<ImageView
android:layout_width="200dp"
android:layout_height="150dp"
android:id="#+id/image"
android:layout_gravity="center"
android:layout_marginTop="10dp" />
<Button
android:layout_width="300dp"
android:layout_height="wrap_content"
android:text="Capture Image"
android:id="#+id/captureimage"
android:layout_gravity="center_horizontal" />
<Button
android:layout_width="300dp"
android:layout_height="wrap_content"
android:text="Save "
android:id="#+id/Dbsave"
android:layout_gravity="center_horizontal" />
<Button
android:layout_width="300dp"
android:layout_height="wrap_content"
android:text="Print"
android:id="#+id/print"
android:layout_gravity="center_horizontal" />
<Button
android:layout_width="300dp"
android:layout_height="wrap_content"
android:text="Discard"
android:id="#+id/button"
android:layout_gravity="center_horizontal" />
</LinearLayout>
</ScrollView>
Here is the print_dialog xml -
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<WebView android:id="#+id/webview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
</RelativeLayout>
Now i want to save the path of a pdf file created and saved in internal storage to be saved in my sqlite database. I know how to store values into database i just wanna know how to get the path of a file stored in my internal storage??
"i just wanna know how to get the path of a file stored in my internal storage??"
Have you tried getFilesDir()? Example.
String path = this.getFilesDir().toString()+"/"+nameOfFile;
You can use the Environment.getExternalStorageDirectory()
This method returns the primary external storage directory.
For example, if you have a folder called /pdf, so the path of your file will be:
Environment.getExternalStorageDirectory() + "/pdf/" + <pd_file_name>
Note: don't be confused by the word "external" here. This directory can better be thought as media/shared storage. It is a filesystem that can hold a relatively large amount of data and that is shared across all applications (does not enforce permissions). Traditionally this is an SD card, but it may also be implemented as built-in storage in a device that is distinct from the protected internal storage and can be mounted as a filesystem on a computer.
More info here