I want to share .gif from my app to facebook,gmail.
hello there is any way to share gif image
i have gif in drawable folder ("giphy.gif")
below are code that i have try , but it give me error.(no attached file)
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
shareGif("giphy");
}
private void shareGif(String resourceName) {
String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
String fileName = "giphy.gif";
File sharingGifFile = new File(baseDir, fileName);
try {
byte[] readData = new byte[1024 * 500];
InputStream fis = getResources().openRawResource(getResources().getIdentifier(resourceName, "drawable", getPackageName()));
FileOutputStream fos = new FileOutputStream(sharingGifFile);
int i = fis.read(readData);
while (i != -1) {
fos.write(readData, 0, i);
i = fis.read(readData);
}
fos.close();
} catch (IOException io) {
}
Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
shareIntent.setType("image/gif");
Uri uri = Uri.fromFile(sharingGifFile);
shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(shareIntent, "Share Emoji"));
}
}
First add permission
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Then you have to save the gif to external storage, and finally load that file.
try {
CopyRAWtoSDCard(mContext,R.drawable.giphy, "giphy");
} catch (IOException e) {
e.printStackTrace();
}
File sdcard = Environment.getExternalStorageDirectory();
File file = new File(sdcard,"/yourapp/giphy.gif");
it.setType("image/*");
it.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
it.putExtra(Intent.EXTRA_SUBJECT, mContext.getString(R.string.app_name));
it.putExtra(Intent.EXTRA_TEXT, "Gif attached");
it.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Intent in = Intent.createChooser(it,"Share");
in.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mContext.startActivity(in);
private void CopyRAWtoSDCard(Context mContext,int id,String name) throws IOException {
String path = Environment.getExternalStorageDirectory() + "/yourapp";
File dir = new File(path);
if (dir.mkdirs() || dir.isDirectory()) {
try {
InputStream in = mContext.getResources().openRawResource(id);
FileOutputStream out = new FileOutputStream(path+ File.separator + name+".gif");
byte[] buff = new byte[1024];
int read = 0;
try {
while ((read = in.read(buff)) > 0) {
out.write(buff, 0, read);
}
} finally {
in.close();
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Works like a Charm!
Related
I have an ImageView in which I loaded a photo from server into it with Glide library.
I have a save button in which I want the image saved to gallery and internal storage when clicked after being loaded. I have tried several possibilities with no success as nothing seem to happen after I click the button.
public class ImagePreviewActivity extends AppCompatActivity {
ImageView imageView;
final File myDir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/SmartPhoto");
boolean success = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image_preview);
imageView = findViewById(R.id.image_preview);
saveImage();
}
private void saveImage() {
TextView mSave = findViewById(R.id.save_img);
mSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
final String fname = "image" + n + ".png";
myDir.mkdirs();
File image = new File(myDir, fname);
imageView.setDrawingCacheEnabled(true);
Bitmap bitmap = imageView.getDrawingCache();
// Encode the file as a PNG image.
FileOutputStream outStream;
try {
outStream = new FileOutputStream(image);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream);
/* 100 to keep full quality of the image */
outStream.flush();
outStream.close();
success = true;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if (success) {
Toast.makeText(getApplicationContext(),"Saved", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(),"not saved", Toast.LENGTH_LONG).show();
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
final Intent scanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
final Uri contentUri = Uri.fromFile(image);
scanIntent.setData(contentUri);
sendBroadcast(scanIntent);
} else {
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://mnt/sdcard/" + Environment.getExternalStorageDirectory())));
}
}
});
}
}
Log Cat
02-24 14:40:41.288 1567-1575/? E/System: Uncaught exception thrown by finalizer
02-24 14:40:41.289 1567-1575/? E/System: java.lang.IllegalStateException: Binder has been finalized!
at android.os.BinderProxy.transactNative(Native Method)
at android.os.BinderProxy.transact(Binder.java:622)
at android.net.INetworkStatsSession$Stub$Proxy.close(INetworkStatsSession.java:476)
at android.app.usage.NetworkStats.close(NetworkStats.java:382)
at android.app.usage.NetworkStats.finalize(NetworkStats.java:118)
at java.lang.Daemons$FinalizerDaemon.doFinalize(Daemons.java:223)
at java.lang.Daemons$FinalizerDaemon.run(Daemons.java:210)
at java.lang.Thread.run(Thread.java:761)
AsyncTask, can be used to download Image .This proccess will be in background thread.
class DownloadImage extends AsyncTask<String,Integer,Long> {
String strFolderName;
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Long doInBackground(String... aurl) {
int count;
try {
URL url = new URL((String) aurl[0]);
URLConnection conexion = url.openConnection();
conexion.connect();
String targetFileName="Name"+".rar";//Change name and subname
int lenghtOfFile = conexion.getContentLength();
String PATH = Environment.getExternalStorageDirectory()+ "/"+downloadFolder+"/";
File folder = new File(PATH);
if(!folder.exists()){
folder.mkdir();//If there is no folder it will be created.
}
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(PATH+targetFileName);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {}
return null;
}
protected void onPostExecute(String result) {
}
}
You can call this class like this new DownloadImage().execute(“yoururl”);
Don't forget to add these permissions in manifest file
<uses-permission android:name="android.permission.INTERNET"> </uses-permission>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
//out oncreate
final File myDir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/SmartPhoto");
boolean success = false;
//inside oncreate
mSave = (TextView) findViewById(R.id.save);
imageView = (ImageView) findViewById(R.id.header_cover_image);
mSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
saveImage();
}
});
public void saveImage()
{
final Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
final String fname = "image" + n + ".png";
myDir.mkdirs();
File image = new File(myDir, fname);
imageView.setDrawingCacheEnabled(true);
Bitmap bitmap = imageView.getDrawingCache();
// Encode the file as a PNG image.
FileOutputStream outStream;
try {
outStream = new FileOutputStream(image);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream);
/* 100 to keep full quality of the image */
outStream.flush();
outStream.close();
success = true;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if (success) {
Toast.makeText(getApplicationContext(),"Saved", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(),"not saved", Toast.LENGTH_LONG).show();
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
final Intent scanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
final Uri contentUri = Uri.fromFile(image);
scanIntent.setData(contentUri);
sendBroadcast(scanIntent);
} else {
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://mnt/sdcard/" + Environment.getExternalStorageDirectory())));
}
}
How do we send GIF image which is present in asset folder to another application using Intent?
I have tried this:
private File getEmojiFile(int position) {
AssetManager assetManager = getApplicationContext().getAssets();
File file = new File(getCacheDir(), mEmojiFileNames[position]);
try {
if (!file.createNewFile()) {
//Emoji File already exists.
return file;
}
} catch (IOException e) {
e.printStackTrace();
}
FileChannel in_chan = null, out_chan = null;
try {
AssetFileDescriptor in_afd = assetManager.openFd(mEmojiFileNames[position]);
FileInputStream in_stream = in_afd.createInputStream();
in_chan = in_stream.getChannel();
FileOutputStream out_stream = new FileOutputStream(file);
out_chan = out_stream.getChannel();
in_chan.transferTo(in_afd.getStartOffset(), in_afd.getLength(), out_chan);
} catch (IOException ioe) {
Log.w("copyFileFromAssets", "Failed to copy file '" + mEmojiFileNames[position] + "' to external storage:" + ioe.toString());
} finally {
try {
if (in_chan != null) {
in_chan.close();
}
if (out_chan != null) {
out_chan.close();
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
return file;
}
and then sending it to another app using Intent:
final Intent intent = new Intent(android.content.Intent.ACTION_SEND);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
EMOJI_IMAGE_TYPE emojiImageType = getImageType(position);
intent.setType("image/gif"));
intent.setPackage(getCurrentAppPackage(SoftKeyboard.this, getCurrentInputEditorInfo()));
PackageManager packageManager = getPackageManager();
if (intent.resolveActivity(packageManager) != null) {
//Save emoji file because current input field supports GIF/PNG.
File emojiFile = getEmojiFile(position);
Uri photoURI = FileProvider.getUriForFile(SoftKeyboard.this, SoftKeyboard.this.getApplicationContext().getPackageName() + ".provider", emojiFile);
intent.putExtra(Intent.EXTRA_STREAM, photoURI);
dialog.dismiss();
hideWindow();
try {
startActivity(intent);
} catch (Exception e) {
e.printStackTrace();
}
} else {
Toast.makeText(SoftKeyboard.this,"This text field does not support "+
"GIF"+" insertion from the keyboard.",Toast.LENGTH_LONG).show();
}
However, after this blank image is coming. Here is tried to send the image to messenger application. It accepted intent but showed blank transparent image:
Scenario: You have a gif file in the Drawable Folder.
Then the code will be:`
private void shareDrawable(Context context,int resourceId,String fileName) {
try {
//create an temp file in app cache folder
File outputFile = new File(context.getCacheDir(), fileName + ".gif");
FileOutputStream outPutStream = new FileOutputStream(outputFile);
//Saving the resource GIF into the outputFile:
InputStream is = getResources().openRawResource(resourceId);
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int current = 0;
while ((current = bis.read()) != -1) {
baos.write(current);
}
FileOutputStream fos = new FileOutputStream(outputFile);
fos.write(baos.toByteArray());
//
outPutStream.flush();
outPutStream.close();
outputFile.setReadable(true, false);
//share file
Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(outputFile));
shareIntent.setType("image/gif");
context.startActivity(shareIntent);
}
catch (Exception e) { Toast.makeText(context, "error", Toast.LENGTH_LONG);}
}
I have to open pdf file stored in asset folder. When I am trying to open the file in Android 6, it shows error. But, no problem with other android versions. I think its the problem with permission. Please help to rectify this error.
Here is my code
....
dialBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
File fileBrochure = new File(Environment.getExternalStorageDirectory() + "/" + email+".pdf");
if (!fileBrochure.exists())
{
CopyAssetsbrochure();
}
/** PDF reader code */
File file = new File(Environment.getExternalStorageDirectory() + "/" + email+".pdf");
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file),"application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
try
{
getApplicationContext().startActivity(intent);
}
catch (ActivityNotFoundException e)
{
Toast.makeText(getApplicationContext(), "Please install any pdf reader App.",
Toast.LENGTH_LONG).show();
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=com.adobe.reader")));
}
}
});
}
private void CopyAssetsbrochure() {
AssetManager assetManager = getAssets();
String[] files = null;
try
{
files = assetManager.list("");
}
catch (IOException e)
{
Log.e("tag", e.getMessage());
}
for(int i=0; i<files.length; i++)
{
String fStr = files[i];
if(fStr.equalsIgnoreCase(email+".pdf"))
{
InputStream in = null;
OutputStream out = null;
try
{
in = assetManager.open(files[i]);
out = new FileOutputStream(Environment.getExternalStorageDirectory() + "/" + files[i]);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
break;
}
catch(Exception e)
{
Log.e("tag", e.getMessage());
}
}
}
}
private void copyFile(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int read;
while((read = in.read(buffer)) != -1){
out.write(buffer, 0, read);
}
}
Did you included: <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
and: <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> in the manifest?
Also I have found this code:
public class SampleActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
CopyReadAssets();
}
private void CopyReadAssets()
{
AssetManager assetManager = getAssets();
InputStream in = null;
OutputStream out = null;
File file = new File(getFilesDir(), "abc.pdf");
try
{
in = assetManager.open("abc.pdf");
out = openFileOutput(file.getName(), Context.MODE_WORLD_READABLE);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch (Exception e)
{
Log.e("tag", e.getMessage());
}
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(
Uri.parse("file://" + getFilesDir() + "/abc.pdf"),
"application/pdf");
startActivity(intent);
}
private void copyFile(InputStream in, OutputStream out) throws IOException
{
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1)
{
out.write(buffer, 0, read);
}
}
}
Here is the link of another answer: Read a pdf file from assets folder
I want use sendFileMessage in sendbird api. It need file value and I want use this file from drawable (or assets). sendBird API
this is snipped code from sendbird
Hashtable<String, Object> info = Helper.getFileInfo(getActivity(), uri);
final String path = (String) info.get("path");
File file = new File(path);
String name = file.getName();
String mime = (String) info.get("mime");
int size = (Integer) info.get("size");
sendFileMessage(file, name, mime, size, "", new BaseChannel.SendFileMessageHandler() {
public void onSent(FileMessage fileMessage, SendBirdException e) {
if (e != null) {
return;
}
mAdapter.appendMessage(fileMessage);
mAdapter.notifyDataSetChanged();
}
});
This code working well which I got uri from open image intent. but I want to use to other purpose and I want to replace this code
File file = new File(path);
become something like
File file = new File(<path or uri from drawable or assets>);
I have tried with uri
Uri uri = Uri.parse("android.resource://com.package.name/raw/filenameWithoutExtension");
File file = new File(uri.getPath());
with inputStream
try {
File f=new File("file name");
InputStream inputStream = getResources().openRawResource(R.raw.myrawfile);
OutputStream out=new FileOutputStream(f);
byte buf[]=new byte[1024];
int len;
while((len=inputStream.read(buf))>0)
out.write(buf,0,len);
out.close();
inputStream.close();
}
catch (IOException e){}
always failed in getting file and return error code ERR_REQUEST_FAILED 800220
Have you tried like below?
String fileName = FILE_NAME;
File cachedFile = new File(this.getActivity().getCacheDir(), fileName);
try {
InputStream is = getResources().openRawResource(R.raw.sendbird_ic_launcher);
FileOutputStream fos = new FileOutputStream(cachedFile);
byte buf[] = new byte[1024];
int len;
while ((len = is.read(buf)) > 0)
fos.write(buf, 0, len);
fos.close();
is.close();
} catch (IOException e) {
e.printStackTrace();
}
groupChannel.sendFileMessage(cachedFile, fileName, "image/jpg", (int) cachedFile.length(), "", new BaseChannel.SendFileMessageHandler() {
#Override
public void onSent(FileMessage fileMessage, SendBirdException e) {
}
});
This works for me.
Does any one has an idea on how to open a PDF file in Android? My code looks this this:
public class SampleActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
CopyReadAssets();
}
private void CopyReadAssets() {
AssetManager assetManager = getAssets();
InputStream in = null;
OutputStream out = null;
File file = new File(getFilesDir(), "git.pdf");
try {
in = assetManager.open("git.pdf");
out = openFileOutput(file.getName(), Context.MODE_WORLD_READABLE);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch (Exception e) {
Log.e("tag", e.getMessage());
}
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(
Uri.parse("file://" + getFilesDir() + "/git.pdf"),
"application/pdf");
startActivity(intent);
}
private void copyFile(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
}
}
Here is the code for opening pdf file from asset folder, but you must have pdf reader installed on your device :
private void CopyAssets() {
AssetManager assetManager = getAssets();
InputStream in = null;
OutputStream out = null;
File file = new File(getFilesDir(), "fileName.pdf");
try {
in = assetManager.open("fileName.pdf");
out = openFileOutput(file.getName(), Context.MODE_WORLD_READABLE);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch (Exception e) {
Log.e("tag", e.getMessage());
}
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(
Uri.parse("file://" + getFilesDir() + "/fileName.pdf"),
"application/pdf");
startActivity(intent);
}
private void copyFile(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
}