How Media Codec in android works ? - Android Q&A, Help & Troubleshooting

Hello,
I am trying to understanding how MediaCodec is used for hardware decoding.
My knowledge in android internal is very limited.
Here is my findings:
There is a xml file which represents the codec details in the android system .
device/ti/omap3evm/media_codecs.xml for an example.
Which means, that If we create a codec from the Java Application with Media Codec
MediaCodec codec = MediaCodec.createDecoderByType(type);
It should be finding out respective coder with the help of xml file.
I am trying to figure our which part of the code is reading xml and find the codec based on given 'type'.
1) Application Layer : MediaCodec codec = MediaCodec.createDecoderByType(type);
2) MediaCodec.java -> [frameworks/base/media/java/android/media/MediaCodec.java ]
public static MediaCodec createDecoderByType(String type) {
return new MediaCodec(type, true /* nameIsType */, false /* encoder */);
}
3) private MediaCodec(
String name, boolean nameIsType, boolean encoder) {
native_setup(name, nameIsType, encoder); --> JNI Call.
}
4)
JNI Implementation -> [ frameworks/base/media/jni/android_media_MediaCodec.cpp ]
static void android_media_MediaCodec_native_setup (..) {
.......
const char *tmp = env->GetStringUTFChars(name, NULL);
sp<JMediaCodec> codec = new JMediaCodec(env, thiz, tmp, nameIsType, encoder); ---> Here
}
from frameworks/base/media/jni/android_media_MediaCodec.cpp
JMediaCodec::JMediaCodec( ..) {
....
mCodec = MediaCodec::CreateByType(mLooper, name, encoder); -> Call goes to libstagefright
....
}
sp<MediaCodec> MediaCodec::CreateByType(
const sp<ALooper> &looper, const char *mime, bool encoder) {
sp<MediaCodec> codec = new MediaCodec(looper);
if (codec->init(mime, true /* nameIsType */, encoder) != OK) {
return NULL;
}
return codec;
}
status_t MediaCodec::init(const char *name, bool nameIsType, bool encoder) {
...
}
I am struck with this flow. If someone points out how to take it forward would help a lot.
thanks.

Related

[HELP] Adding a Toast message to Decompress activity

Hi everyone,
I am currently working on my first app which grabs a ZIP from the internet and the extracts it to a certain location. Everything works great but I can not figure out how to show a Toast message when the extraction operation is done.
The code I am using for unzipping is:
Code:
package mmarin.test.download;
import android.util.Log;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
/**
*
* @author jon
*/
public class Decompress{
private String _zipFile;
private String _location;
byte[] buffer = new byte[1024];
int length;
public Decompress(String zipFile, String location) {
_zipFile = zipFile;
_location = location;
_dirChecker("");
}
public void unzip() {
try {
FileInputStream fin = new FileInputStream(_zipFile);
ZipInputStream zin = new ZipInputStream(fin);
ZipEntry ze = null;
while ((ze = zin.getNextEntry()) != null) {
Log.v("Decompress", "Unzipping " + ze.getName());
if(ze.isDirectory()) {
_dirChecker(ze.getName());
} else {
FileOutputStream fout = new FileOutputStream(_location + ze.getName());
while ((length = zin.read(buffer))>0) {
fout.write(buffer, 0, length);
}
zin.closeEntry();
fout.close();
}
}
zin.close();
} catch(Exception e) {
Log.e("Decompress", "unzip", e);
}
}
private void _dirChecker(String dir) {
File f = new File(_location + dir);
if(!f.isDirectory()) {
f.mkdirs();
}
}
}
I am calling the Decompress activity through a button:
Code:
Button decompress = (Button)findViewById(R.id.button1);
decompress.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
String zipFile = Environment.getExternalStorageDirectory() + "/IPM/Splash.zip";
String unzipLocation = Environment.getExternalStorageDirectory() + "/IPM/Splash/";
Decompress d = new Decompress(zipFile, unzipLocation);
d.unzip();
}
});
I found this here: http://www.jondev.net/articles/Unzipping_Files_with_Android_(Programmatically) and it works great.
As I said above, only issue is displaying a message that everything is done.
Can someone please help me out?
Thank you!
Please use the Q&A Forum for questions &
Read the Forum Rules Ref Posting
Moving to Q&A
Put the toast after zin.close()
www.stackoverflow.com
Here you can find what you want
Xperian using xda app
http://stackoverflow.com/questions/9824772/toast-after-email-intent-message
Check this
Xperian using xda app
RoberGalarga said:
Put the toast after zin.close()
Click to expand...
Click to collapse
Hey,
I tried this but it doesn't work. I used this statement:
Code:
Toast.makeText(this, "Extraction complete", "LENGTH_SHORT").show();
and I got this error message: The method makeText(Context, CharSequence, int) in the type Toast is not applicable for the arguments (Decompress, String, String).
Help?
The method makeText(Context, CharSequence, int) in the type Toast is not applicable for the arguments (Decompress, String, String)
What the above line means is that you need to pass a Context object, a CharSequence object and an int. You are passing the wrong object types (Decompress, String, String).
The example you saw used the Toast in the activity class itself, that is why the first value passed was a this. The "LENGTH_SHORT" is actually a constant Toast.LENGTH_SHORT.
I am guessing you are making the button object in your main activity class. So i'd suggest making an additional method for the activity class that looks like this
Code:
public void displayToast(CharSequence cs)
{
Toast.makeText(this, cs, Toast.LENGTH_SHORT).show();
}
and then make the following change to your code
Code:
Button decompress = (Button)findViewById(R.id.button1);
decompress.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
String zipFile = Environment.getExternalStorageDirectory() + "/IPM/Splash.zip";
String unzipLocation = Environment.getExternalStorageDirectory() + "/IPM/Splash/";
Decompress d = new Decompress(zipFile, unzipLocation);
d.unzip();
// Add the following line
displayToast("Unzip complete");
}
});
Let me know if it worked for you.
The_R said:
The method makeText(Context, CharSequence, int) in the type Toast is not applicable for the arguments (Decompress, String, String)
What the above line means is that you need to pass a Context object, a CharSequence object and an int. You are passing the wrong object types (Decompress, String, String).
The example you saw used the Toast in the activity class itself, that is why the first value passed was a this. The "LENGTH_SHORT" is actually a constant Toast.LENGTH_SHORT.
I am guessing you are making the button object in your main activity class. So i'd suggest making an additional method for the activity class that looks like this
Code:
public void displayToast(CharSequence cs)
{
Toast.makeText(this, cs, Toast.LENGTH_SHORT).show();
}
and then make the following change to your code
Code:
Button decompress = (Button)findViewById(R.id.button1);
decompress.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
String zipFile = Environment.getExternalStorageDirectory() + "/IPM/Splash.zip";
String unzipLocation = Environment.getExternalStorageDirectory() + "/IPM/Splash/";
Decompress d = new Decompress(zipFile, unzipLocation);
d.unzip();
// Add the following line
displayToast("Unzip complete");
}
});
Let me know if it worked for you.
Click to expand...
Click to collapse
PERFECT! You're amazing!

[Q] How to use multi-threaded class in bootanimation?

Hi Droid-expert
For stock bootanimation in JB, there is a single threaded animation process/class inside. If I'd like to implement the power-on sound/tune as well. What's the best programming scheme/model it could be?
So far, by my understanding, I did something in BootAnimation.cpp in the following:
Did I do wrong? The handset boots up, it shows the animation first, and then the sound is played.
However, in a normal AOS adb shell session, try to run bootanimation, and it works fine (I mean both animation and sound are played at the same time)
Does the init is multi-threaded?
Anthony
class PlayerListener: public MediaPlayerListener, public Thread
{
public:
PlayerListener(): Thread(false), mp(NULL) {}
~PlayerListener() { delete mp; mp = NULL; }
virtual void notify(int, int, int, const Parcel *) {}
virtual bool threadLoop();
virtual status_t readyToRun();
private:
MediaPlayer* mp;
};
// ----------------------------------------------------------------------
bool PlayerListener::threadLoop()
{
if (mp != NULL)
mp->start();
sleep(100);
requestExit();
return false;
}
status_t PlayerListener::readyToRun()
{
int index = 7;
audio_devices_t device;
bool r;
mp = new MediaPlayer();
mp->setListener(this);
if (mp->setDataSource(SYSTEM_BOOTANIMATION_SOUND_FILE, NULL) == NO_ERROR) {
mp->setAudioStreamType(AUDIO_STREAM_ENFORCED_AUDIBLE);
mp->prepare();
mp->setLooping(false);
}
// AudioSystem::getStreamVolumeIndex(AUDIO_STREAM_ENFORCED_AUDIBLE, &index);
device = AudioSystem::getDevicesForStream(AUDIO_STREAM_ENFORCED_AUDIBLE);
r = AudioSystem::setStreamVolumeIndex(AUDIO_STREAM_ENFORCED_AUDIBLE, index, device);
r = AudioSystem::getStreamVolumeIndex(AUDIO_STREAM_ENFORCED_AUDIBLE, &index, device);
if (index != 0) {
mp->seekTo(0);
// mp->start();
}
return NO_ERROR;
}
bool BootAnimation::threadLoop()
{
bool r;
sp<PlayerListener> player = new PlayerListener();
player->run("BootAnimatedMelody", PRIORITY_AUDIO);
if (mAndroidAnimation) {
r = android();
} else {
r = movie();
}

[Q] can't transform xml+xsl(with exslt) to html

Hi guys, I am developing an app which loads a xml and a xsl and loads the resulting html, displaying it on the screen. It works perfectly when the xsl does not have exslt functions. However, when it does contain exslt functions, it doesn't work.
The code is rather small, so I'm posting it here:
Code:
public class MainActivity extends Activity {
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
WebView webview = new WebView(this);
setContentView(webview);
Source xmlSource = new StreamSource(this.getResources().openRawResource(R.raw.xml2));
Source xsltSource = new StreamSource(this.getResources().openRawResource(R.raw.xsl2));
TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer = null;
ByteArrayOutputStream output = null;
StreamResult result;
try
{
transformer = tFactory.newTransformer(xsltSource);
output = new ByteArrayOutputStream();
result = new StreamResult(output);
transformer.transform(xmlSource, result);
} catch (TransformerException e)
{
e.printStackTrace();
}
ByteArrayInputStream input = new ByteArrayInputStream(output.toByteArray());
String html = new Scanner(input,"UTF-8").useDelimiter("\\A").next();
webview.loadData(html, "text/html", "UTF-8");
}
[user=439709]@override[/user]
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
I have attached a zip file containing 5 files: xml,xsl, xml2,xsl2, logcat.
I get the errors with xml2 and xsl2.
I'm using the eclipse IDE, ADT bundle thing. In addition, I have tried an equivalent code in netbeans:
Code:
public class JavaApplication4 {
/**
* [user=955119]@param[/user] args the command line arguments
*/
public static void main(String[] args) throws TransformerConfigurationException, TransformerException, FileNotFoundException {
Source xmlSource = new StreamSource("xml2.xml");
Source xsltSource = new StreamSource("xsl2.xsl");
TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer = tFactory.newTransformer(xsltSource);
ByteArrayOutputStream output = new ByteArrayOutputStream();
StreamResult result = new StreamResult(output);
transformer.transform(xmlSource, result);
ByteArrayInputStream input = new ByteArrayInputStream(output.toByteArray());
String html = new Scanner(input,"UTF-8").useDelimiter("\\A").next();
System.out.println(html);
}
}
which, to my surprise, works for both xml and xsl.
Please help me, I've been trying to make it work for hours...I've tried many stuff, different codes...but it doesn't seem to have anything to do with my code.
Thank you for your time.

[Q] Google Map is Not Working in Android Emulator.

Hi there
I am trying to Run google Map on Android Emulator But Map is Not Working.I mean Google Map is displaying in Fragment But there is Not any Markers that I place in My Code.
This is My activity class
Java:
double mLatitude=0;
double mLongitude=0;
private GoogleMap map;
Spinner mSprPlaceType;
String[] mPlaceType=null;
String[] mPlaceTypeName=null;
[user=5448622]@Suppress[/user]Lint("NewApi")
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_places1);
// Array of place types
mPlaceType = getResources().getStringArray(R.array.place_type);
// Array of place type names
mPlaceTypeName = getResources().getStringArray(R.array.place_type_name);
// Creating an array adapter with an array of Place types
// to populate the spinner
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, mPlaceTypeName);
// Getting reference to the Spinner
mSprPlaceType = (Spinner) findViewById(R.id.spr_place_type);
// Setting adapter on Spinner to set place types
mSprPlaceType.setAdapter(adapter);
Button btnFind;
// Getting reference to Find Button
btnFind = ( Button ) findViewById(R.id.button1);
// Getting Google Play availability status
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());
if(status!=ConnectionResult.SUCCESS){ // Google Play Services are not available
int requestCode = 10;
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode);
dialog.show();
}
else
{
map=((MapFragment)getFragmentManager().findFragmentById(R.id.map)).getMap();
map.setMyLocationEnabled(true);
// Getting LocationManager object from System Service LOCATION_SERVICE
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
// Creating a criteria object to retrieve provider
Criteria criteria = new Criteria();
// Getting the name of the best provider
String provider = locationManager.getBestProvider(criteria, true);
// Getting Current Location From GPS
Location location = locationManager.getLastKnownLocation(provider);
if(location!=null){
onLocationChanged(location);
}
locationManager.requestLocationUpdates(provider, 20000, 0, this);
// Setting click event lister for the find button
btnFind.setOnClickListener(new OnClickListener() {
[user=439709]@override[/user]
public void onClick(View v) {
int selectedPosition = mSprPlaceType.getSelectedItemPosition();
String type = mPlaceType[selectedPosition];
StringBuilder sb = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
sb.append("location="+mLatitude+","+mLongitude);
sb.append("&radius=10000");
sb.append("&types="+type);
sb.append("&sensor=true");
sb.append("&key=AIzaSyCba6q28XzWhcq5wPaB7ek7HWqh3Sq2Q3A");
// Creating a new non-ui thread task to download json data
PlacesTask placesTask = new PlacesTask();
// Invokes the "doInBackground()" method of the class PlaceTask
placesTask.execute(sb.toString());
}
});
}
}
/** A method to download json data from url */
private String downloadUrl(String strUrl) throws IOException{
String data = "";
InputStream iStream = null;
HttpURLConnection urlConnection = null;
try{
URL url = new URL(strUrl);
// Creating an http connection to communicate with url
urlConnection = (HttpURLConnection) url.openConnection();
// Connecting to url
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while( ( line = br.readLine()) != null){
sb.append(line);
}
data = sb.toString();
br.close();
}catch(Exception e){
Log.d("Exception while downloading url", e.toString());
}finally{
iStream.close();
urlConnection.disconnect();
}
return data;
}
/** A class, to download Google Places */
private class PlacesTask extends AsyncTask<String, Integer, String>{
String data = null;
// Invoked by execute() method of this object
[user=439709]@override[/user]
protected String doInBackground(String... url) {
try{
data = downloadUrl(url[0]);
}catch(Exception e){
Log.d("Background Task",e.toString());
}
return data;
}
// Executed after the complete execution of doInBackground() method
[user=439709]@override[/user]
protected void onPostExecute(String result){
ParserTask parserTask = new ParserTask();
// Start parsing the Google places in JSON format
// Invokes the "doInBackground()" method of the class ParseTask
parserTask.execute(result);
}
}
/** A class to parse the Google Places in JSON format */
private class ParserTask extends AsyncTask<String, Integer, List<HashMap<String,String>>>{
JSONObject jObject;
// Invoked by execute() method of this object
[user=439709]@override[/user]
protected List<HashMap<String,String>> doInBackground(String... jsonData) {
List<HashMap<String, String>> places = null;
PlaceJSONParser placeJsonParser = new PlaceJSONParser();
try{
jObject = new JSONObject(jsonData[0]);
/** Getting the parsed data as a List construct */
places = placeJsonParser.parse(jObject);
}catch(Exception e){
Log.d("Exception",e.toString());
}
return places;
}
// Executed after the complete execution of doInBackground() method
[user=439709]@override[/user]
protected void onPostExecute(List<HashMap<String,String>> list){
// Clears all the existing markers
map.clear();
for(int i=0;i<list.size();i++){
// Creating a marker
MarkerOptions markerOptions = new MarkerOptions();
// Getting a place from the places list
HashMap<String, String> hmPlace = list.get(i);
// Getting latitude of the place
double lat = Double.parseDouble(hmPlace.get("lat"));
// Getting longitude of the place
double lng = Double.parseDouble(hmPlace.get("lng"));
// Getting name
String name = hmPlace.get("place_name");
// Getting vicinity
String vicinity = hmPlace.get("vicinity");
LatLng latLng = new LatLng(lat, lng);
// Setting the position for the marker
markerOptions.position(latLng);
// Setting the title for the marker.
//This will be displayed on taping the marker
markerOptions.title(name + " : " + vicinity);
// Placing a marker on the touched position
map.addMarker(markerOptions);
}
}
}
[user=439709]@override[/user]
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.show_places1, menu);
return true;
}
[user=439709]@override[/user]
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
[user=439709]@override[/user]
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
mLatitude=location.getLatitude();
mLongitude=location.getLongitude();
LatLng latLng = new LatLng(mLatitude, mLongitude);
map.moveCamera(CameraUpdateFactory.newLatLng(latLng));
map.animateCamera(CameraUpdateFactory.zoomTo(12));
}
[user=439709]@override[/user]
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
[user=439709]@override[/user]
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
[user=439709]@override[/user]
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
}
And This is My Emulator Defination
Phone_Test2
Nexus S(4.0,480*800hdpi)
Google API(x86 System Image)
Intel Atomx86
HVGA
RAM:500MB
VM Heap:16
Internal Storage:200
SD Card:50
Click to expand...
Click to collapse
I have added all Jars and Permisiion in Manifest.Application is Working fine on Android Powerd Mobile Phone But Not on Android Emulator
any guess?
Thanks

How to set proxy in a webview (Android 6.0 Marshmallow)

Hi all,
I know how to set proxy in a webview under Android 4.4 and less, using java reflection.
But anyone knows how to set a webview proxy under Android 6.0 ? Unfortunatly my methods don't work on this Android version ...
Thanks a lot in advance !
[EDIT] Solved, see post #2
Solved by projection :
Code:
private static boolean setProxyKKPlus(WebView webView, String host, int port, String exclusion, String applicationClassName) {
LOG.warn("try to setProxyKKPlus");
Context appContext = webView.getContext().getApplicationContext();
System.setProperty("http.proxyHost", host);
System.setProperty("http.proxyPort", port + "");
System.setProperty("http.nonProxyHosts", exclusion);
System.setProperty("https.proxyHost", host);
System.setProperty("https.proxyPort", port + "");
System.setProperty("https.nonProxyHosts", exclusion);
try {
Class applictionCls = Class.forName(applicationClassName);
Field loadedApkField = applictionCls.getField("mLoadedApk");
loadedApkField.setAccessible(true);
Object loadedApk = loadedApkField.get(appContext);
Class loadedApkCls = Class.forName("android.app.LoadedApk");
Field receiversField = loadedApkCls.getDeclaredField("mReceivers");
receiversField.setAccessible(true);
ArrayMap receivers = (ArrayMap) receiversField.get(loadedApk);
for (Object receiverMap : receivers.values()) {
for (Object rec : ((ArrayMap) receiverMap).keySet()) {
Class clazz = rec.getClass();
if (clazz.getName().contains("ProxyChangeListener")) {
Method onReceiveMethod = clazz.getDeclaredMethod("onReceive", Context.class, Intent.class);
Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Bundle extras = new Bundle();
List<String> exclusionsList = new ArrayList<>(1);
exclusionsList.add(exclusion);
ProxyInfo proxyInfo = ProxyInfo.buildDirectProxy(host, port, exclusionsList);
extras.putParcelable("android.intent.extra.PROXY_INFO", proxyInfo);
intent.putExtras(extras);
onReceiveMethod.invoke(rec, appContext, intent);
}
}
}
} catch (Exception e) {
LOG.warn("setProxyKKPlus - exception : {}", e);
return false;
}
return true;
}
parameters
what is exclusion and applicationClassName parameters? Im trying to setup proxy on Api 21+
Is anyone able to use buildPacProxy method instead of buildDirectProxy method of ProxyInfo to set the proxy of webview?

Categories

Resources