Intent filter for receiving intents - android

I have one question about android programming. I have an file explorer app and I want to implement various functions like open photos music etc. But in app itself, not sending intents to other apps! So, my question is, what intent filter I should use for "plugin" app for receiving "opening" intent ?
This is my code
public static void openFile(final Context context, final File target) {
final String mime = MimeTypes.getMimeType(target);
final Intent i = new Intent(Intent.ACTION_VIEW);
if (mime != null) {
i.setDataAndType(Uri.fromFile(target), mime);
} else {
i.setDataAndType(Uri.fromFile(target), "*/*");
}
if (context.getPackageManager().queryIntentActivities(i, 0).isEmpty()) {
Toast.makeText(context, R.string.cantopenfile, Toast.LENGTH_SHORT)
.show();
return;
}
try {
context.startActivity(i);
} catch (Exception e) {
Toast.makeText(context,
context.getString(R.string.cantopenfile) + e.getMessage(),
Toast.LENGTH_SHORT).show();
}
}

ok let's assume you want to open an image from your own explorer
create a new Activity let's say ImageActivity, then you simply implement an ImageViewer inside your activity and from the calling Activity simply send an intent with an Extra Bundle containing your image Bytes
EDIT
SENDING ACTIVITY
Intent intent = new Intent(MainActivity.this, ImageActivity.class);
ImageView imageView = findViewById(R.id.image).getDrawable();
imageView.buildDrawingCache();
Bitmap image = imageView.getDrawingCache();
Bundle extras = new Bundle();
extras.putParcelable("imagebitmap", image);
intent.putExtras(extras);
startActivity(intent);
Receiving Activity ImageActivity
Bundle extras = getIntent().getExtras();
Bitmap bmp = (Bitmap) extras.getParcelable("imagebitmap");
ImageView image = findViewById(R.id.image);
image.setImageBitmap(bmp );

Related

Android : Share drawable resource with other apps

In my activity I have an ImageView. I want ,when user click on it, a dialog opens (like intent dialogs) that show list of apps which can open image than user can choose a app and show the image with that app.
my activity code :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ImageView iv = (ImageView) findViewById(R.id.imageid);
iv.setImageResource(R.drawable.dish);
iv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//here is where I want a dialog that I mentioned show
}
});
}// end onCreate()
You can't pass a bitmap to an intent.
From what I see you want to share a drawable from your resources. So first you have to convert the drawable to a bitmap. And then You have to save the bitmap to the external memory as a file and then get a uri for that file using Uri.fromFile(new File(pathToTheSavedPicture)) and pass that uri to the intent like this.
shareDrawable(this, R.drawable.dish, "myfilename");
public void shareDrawable(Context context,int resourceId,String fileName) {
try {
//convert drawable resource to bitmap
Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), resourceId);
//save bitmap to app cache folder
File outputFile = new File(context.getCacheDir(), fileName + ".png");
FileOutputStream outPutStream = new FileOutputStream(outputFile);
bitmap.compress(CompressFormat.PNG, 100, outPutStream);
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/png");
context.startActivity(shareIntent);
}
catch (Exception e) { Toast.makeText(context, "error", Toast.LENGTH_LONG).show();
}
}
You have to startActivity using intent of type Intent.ACTION_VIEW-
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(<your_image_uri>, "image/*");
startActivity(intent);
Create a chooser by using the following code. You can add it in the part where you say imageview.setonclicklistener().
Intent intent = new Intent();
// Show only images, no videos or anything else
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
// Always show the chooser (if there are multiple options available)
startActivityForResult(Intent.createChooser(intent, "Select Picture"), 1);

Send bitmap to image picker / gallery application

I'm trying to add an option in my app to send an image inside my app to other app like gallery or image picker/selectors. For example, a third-party launcher, which wants to select an icon that is inside my app.
I'm using a RecyclerView grid, to show the list of icons.
This is my code to load the icons:
icons = mContext.getResources().getStringArray(R.array.icons);
list = new ArrayList<String>(Arrays.asList(iconNames));
loadIcon(list);
private void loadIcon(List<String> list) {
mThumbs = new ArrayList<>();
for (String extra : list) {
int res = mContext.getResources().getIdentifier(extra, "drawable", p);
if (res != 0) {
final int thumbRes = mContext.getResources().getIdentifier(extra, "drawable", p);
if (thumbRes != 0)
mThumbs.add(thumbRes);
}
}
}
And this is the code in the OnClick of grid item:
Intent intent = new Intent();
Bitmap bitmap = null;
try {
bitmap = BitmapFactory.decodeResource(mContext.getResources(), mThumbs.get(position));
} catch (Exception e) {
Log.v("Icons Picker Error", "Picker error: " + Log.getStackTraceString(e));
}
if (bitmap != null) {
intent.putExtra("icon", bitmap);
mContext.setResult(Activity.RESULT_OK, intent);
} else {
mContext.setResult(Activity.RESULT_CANCELED, intent);
}
mContext.finish();
Apparently, icon bitmap is created properly, but when trying to send it to the selector, nothing is sent.
I'm not sure what could be wrong in the code, but I hope someone could help me with this. Thanks in advance.
you can display a chooser (all apps capable of performing the task are displayed for the user to select from). here is a code snippet to do that:
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_DOCUMENT);
shareIntent.setType("image/*");
shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(shareIntent, "Choose an app to share the image"));
For this to work, you need to pass the Uri of the bitmap. One way of achieving this is to save the bitmap in a temporary file and then use FileProvider.getUriForFile() to get the uri of the temp file.
good luck
clive

Moving the picture captured to the next activity

Am trying to put the picture captured by the user in the second activity. Every time I capture the picture it takes me to the nextActivity but the problem am facing now is how to put the image captured inside the next activity so the user can see it
Please any one can guide me or direct me on how should i do it?
This is my code
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAM_REQUEST) {
if (resultCode == RESULT_OK) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
Intent i = new Intent(this, PostActivity.class);
i.putExtra("name", thumbnail);
startActivity(i);
}
}
}
You can use following code to send data through Intent
Intent intent=new Intent(CurrentActivity.this,SecondActivity.class);
intent.putExtra("imagepath",path);
startActivity(intent);
Code To Receive Data that sent through Intent in SecondActivity
Bundle b=getIntent().getExtras();
String path=b.getString("imagepath");
Add an image path to intent extras and get it in the second activity.
Send Image URI using Intent Extras in between Activities.
Intent i = new Intent(this, SecondActivity.class);
i.putExtra("uri",uri);
startActivity(i);
As you Receive Bitmap on onActivityResult method. so you can try with following code to pass image to theNextActivity.
1) Convert Bitmap to Byte Array
Bitmap mBitmap = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream stream = new ByteArrayOutputStream();
mBitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
// Pass it to intent to send in NextActitivy
Intent intent = new Intent(this, NextActivity.class);
intent.putExtra("captured_image", byteArray);
startActivity(intent);
2) Get byte from bundle on NextActivity at onCreate() method
Bundle mBundle = getIntent().getExtras();
byte[] mBytes = mBundle.getByteArray("captured_image");
Bitmap mBitmap = BitmapFactory.decodeByteArray(mBytes, 0, mBytes.length);
ImageView mImageView = (ImageView) findViewById(R.id.imageView1);
mImageView.setImageBitmap(mBitmap);

Android Training: Capturing Photo example

I'm quite new to android but have been working through the examples on google's site - I'm on this one: http://developer.android.com/training/camera/index.html
This is a "simple" example on using the camera function on android. There is a button that calls up an intent. The intent is displayed below.
private void dispatchTakePictureIntent(int actionCode) {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
switch(actionCode) {
case ACTION_TAKE_PHOTO_B:
File f = null;
try {
f = setUpPhotoFile();
mCurrentPhotoPath = f.getAbsolutePath();
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
} catch (IOException e) {
e.printStackTrace();
f = null;
mCurrentPhotoPath = null;
}
break;
default:
break;
} // switch
startActivityForResult(takePictureIntent, actionCode);
As you can see above, the intent putExtra of key MediaStore.EXTRA_OUTPUT. On android's website: http://developer.android.com/reference/android/provider/MediaStore.html#EXTRA_OUTPUT it says that the MediaStore.EXTRA_OUTPUT has a constant value of "output".
Once the user clicks on a button, the intent is called and the following is an extract of the onActivityResult method given in the code:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case ACTION_TAKE_PHOTO_S: {
if (resultCode == RESULT_OK) {
handleSmallCameraPhoto(data);
}
break;
} // ACTION_TAKE_PHOTO_S
A method handleSmallCameraPhoto(data); is then called. Here is the code for handleSmallCameraPhoto.
private void handleSmallCameraPhoto(Intent intent) {
Bundle extras = intent.getExtras();
mImageBitmap = (Bitmap) extras.get("data");
mImageView.setImageBitmap(mImageBitmap);
mVideoUri = null;
mImageView.setVisibility(View.VISIBLE);
mVideoView.setVisibility(View.INVISIBLE);
}
Now in the above method, we want to getExtras from the intent - so what was putExtra in under method dispatchTakePictureIntent we are extracting.
We see this line here.
mImageBitmap = (Bitmap) extras.get("data");
Isn't the "data" inside extras.get("data") a key for android to extract the extra data for? From dispatchTakePictureIntent, the key was MediaStore.EXTRA_OUTPUT which had a constant of "output" not "data", how does android know what is associated with "data"?
Ok. I actually found the answer on the android website. The answer is here: http://developer.android.com/training/camera/photobasics.html#TaskPath under the heading "Get the Thumbnail"
This is a special case and android saves thumbnails with the key called "data" in the intent.
The site says: This thumbnail image from "data" might be good for an icon, but not a lot more.

Need to know about app chooser in android

I have a list of files in listview .. these files actually reside on sd card. Now i want to open these files by using an app picker. I.e if this file is an image it should show all applications in my phone that can open jpg type files in application chooser box.
How can i do this .. can someone give me any idea about it?
Any help is appreciated :)
Thanks in advance
I found dis piece of code ..how can i use it in my application?
public class Redirector {
public static void showActivityWithChooser( Context context, int chooserLabelTitleId, Intent intent ) {
try {
context.startActivity( Intent.createChooser( intent,
context.getResources().getString( chooserLabelTitleId )) );
} catch( Exception e ) {
e.printStackTrace();
}
}
public static void viewInExternalApplication( Context context, String url ) {
Intent intent = new Intent( Intent.ACTION_VIEW );
intent.setData( Uri.parse( url ) );
intent.addFlags( Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET );
showActivityWithChooser( context, R.string.open_chooser_title, intent );
}
}
String path = Environment.getExternalStorageDirectory().getAbsolutePath()
+ "/YOUR_PATH_TO_Images/";
try {
if (f.exists()) {
File file = new File(path
+ listViewArray.get(position).getImageName());
Intent target = new Intent(Intent.ACTION_VIEW);
target.setDataAndType(Uri.fromFile(file),
"image/*");
target.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
Intent intent1 = Intent.createChooser(target,
"Open With");
startActivity(intent1);
}
} catch (ActivityNotFoundException e) {
Toast.makeText(getActivity(), "No Pdf found",
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
Just send the intent. Android will show an app chosser itself, if more than one app capable of showing the specified file type is installed, or start the app directly, if there's just one (or the user selected "always"/"remember my choice" in the app chooser)
To get the applications that can successfully open a given intent you'll use the PackageManager. Simply construct the intent as above and then use this code to get the applications that can handle the intent.
Intent myIntent = new Intent();
myIntent.setAction(Intent.ACTION_VIEW);
myIntent.addCategory("android.intent.category.LAUNCHER");
myIntent.setType("mp3");
PackageManager manager = getPackageManager();
List<ResolveInfo> info = manager.queryIntentActivities(myIntent,PackageManager.MATCH_DEFAULT_ONLY);
This will give you all the information on the programs that can handle the intent, including icon, and packagename. You can then create a dialog box with these options and save the option the user chooses.
1.This is question is related to Mime type
First get extenstion of file and set type of mime used by element into list
private String extenstionFile(String url) {
if (url.indexOf("?")>-1) {
url = url.substring(0,url.indexOf("?"));
}
if (url.lastIndexOf(".") == -1) {
return null;
} else {
String ext = url.substring(url.lastIndexOf(".") );
if (ext.indexOf("%")>-1) {
ext = ext.substring(0,ext.indexOf("%"));
}
if (ext.indexOf("/")>-1) {
ext = ext.substring(0,ext.indexOf("/"));
}
return ext.toLowerCase();
}
}
Than open supported type of application list:-
MimeTypeMap myMime = MimeTypeMap.getSingleton();
Intent newIntent = new Intent(android.content.Intent.ACTION_VIEW);
//Intent newIntent = new Intent(Intent.ACTION_VIEW);
String mimeType = myMime.getMimeTypeFromExtension(extenstionFile(getFile().toString()).substring(1));
newIntent.setDataAndType(Uri.fromFile(getFile()),mimeType);
newIntent.setFlags(newIntent.FLAG_ACTIVITY_NEW_TASK);
try {
_context.startActivity(newIntent);
} catch (android.content.ActivityNotFoundException e) {
Toast.makeText(_context, "No handler for this type of file.", 4000).show();
}
After selecting the file please check whic file is it (ex pdf , jpg) , After that create an ACTION_VIEW intent and set the type of intent according to selected file type. Now brocast the intent , System itself will show you the list of applications thats supports the viewing of yor file.
Check below link you will get better idea.
http://developer.android.com/guide/components/intents-filters.html

Categories

Resources