Skip to content
Search

Android:Context

lastmod 2018-08-17created 2014-01-046 edits

An interface for accessing global information about the application environment. It is an Abstract class whose actual implementation is provided by the Android system. Through Context, you can not only access application-specific resources and classes, but also call APIs to perform application-level operations - launching an Activity, broadcasting an Intent, receiving an Intent, and so on. In short, Context is an Abstract class that plays two main roles.

  • Accessing the information the system manages about the application
  • Calling the APIs provided by Android system services

getContext() vs getApplicationContext() vs getBaseContext()

View.getContext()
Returns the context of the currently running View, which is usually the context of the currently active activity.
Activity.getApplicationContext()
Returns the application's Context. Rather than just the current activiy's context, the Context tied to the application's lifeCycle is used.
ContextWrapper.getBaseContext()
Used when you want to access a Context other than your own. A ContextWrapper can reference a Context via getBaseContext().
this
Same as View.getContext().

How to access media content

The first way uses MediaColumns.Data.

Cursor c = getContentResolver().query(Uri.parse"content://media/external/images/media/1"), null,null,null,null);
c.moveToNext();
String path = c.getString(c.getColumnIndex(MediaStore.MediaColumns.DATA));
Uri uri = Uri.fromFile(new File(path));
Log.e("URI", uri.toString());
c.close();

The second way uses the content ID.

String fileStr = "file:///sdcard/DCIM/Camera/2010-03-08%2013.42.44.jpg";
Uri fileUri = Uri.parse(fileStr);
String filePath = fileUri.getPath();
Cursor c = getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,null, "_data = '" + filePath + "'", null,null);
c.moveToNext();
int id = c.getInt(0);
Uri uri = ContentUris.withAppendedId(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, id);
Log.e("URI", uri.toString());

Favorite site

References


  1. Android_context.pdf ↩