Payday Loan Payday Loan

Archive for the ‘Multimedia’ Category

How to make a layout animation in android

Hi,
I want to show you how to animate a layout in android.
Let’s say you want to animate a group of views and not only a view. I will give you example a LinearLayout.
For referring to a LinearLayout you need to have an id for it in xml file like this:

<LinearLayout   android:id="@+id/myLayoutId"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content">
</LinearLayout>

Then you will search for this layout in your java code and apply TransitionAnimation:

onCreate(){
toolbarWidget = (LinearLayout)findViewById(R.id.toolbarWidget);
toolbarWidget.startAnimation(inFromRightAnimation());
}
 private Animation inFromRightAnimation() {
 
        Animation inFromRight = new TranslateAnimation(
                Animation.RELATIVE_TO_PARENT,  +1.0f, Animation.RELATIVE_TO_PARENT,  0.0f,
                Animation.RELATIVE_TO_PARENT,  0.0f, Animation.RELATIVE_TO_PARENT,   0.0f
        );
        inFromRight.setDuration(1000);
        inFromRight.setInterpolator(new AccelerateInterpolator());
        return inFromRight;
    }

Hope this is usefull for you.

||||| 1 I Like It! |||||

Hi,
I want to show you how you can make a RotateAnimation in android. This rotate animation it will be around the self center.

ImageView refresh = (ImageView)view.findViewById(R.id.refreshimage);
            RotateAnimation anim = new RotateAnimation(0f, 360f,
                    Animation.RELATIVE_TO_SELF, 0.5f,
                    Animation.RELATIVE_TO_SELF, 0.5f);
            anim.setInterpolator(new LinearInterpolator());
            anim.setRepeatCount(Animation.INFINITE);       
            anim.setDuration(1000);
            refresh.startAnimation(anim);
||||| 0 I Like It! |||||

Hi,
Because my latest post was about handling images, I will show you how to avoid Out Of Memory Exception caused by handling large images.
As you know, the available memory for an application is limited and loading large bitmaps will trigger an Out Of Memory Exception. You can avoid OOM exceptions by scaling the images to a smaller size as follows:

For getting the size of the bitmap without loading it in memory we’ll set the field inJustDecodeBounds to true, as the documentation says:
“If set to true, the decoder will return null (no bitmap), but the out… fields will still be set, allowing the caller to query the bitmap without having to allocate the memory for its pixels.” – so we’ll be able to get the bitmap size from outWidth and outHeight fields.

 
private static final int MAXIMUM_SIZE = 900; // the maximum size, in pixels, that width or height (depending
//which is greater) will have after scaling; 
 
private Bitmap getScaledImage(String imagePath) {
    BitmapFactory.Options o = new BitmapFactory.Options();
    o.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(imagePath, o);
 
    int width_tmp = o.outWidth;
    int height_tmp = o.outHeight;
 
    if(MAXIMUM_SIZE < Math.max(width_tmp, height_tmp))
    {
         return scaleImage(imagePath, width_tmp, height_tmp);
    } else {
	 return BitmapFactory.decodeFile(imagePath);
    }
}
 
private Bitmap scaleImage(String imagePath, int width_tmp, int height_tmp) {
    int scale = getScale(width_tmp, height_tmp);
 
    BitmapFactory.Options o2 = new BitmapFactory.Options();
    o2.inSampleSize = scale;
    return BitmapFactory.decodeFile(path, o2);
}
 
private int getScale(int width_tmp, int height_tmp) {
    int size = Math.max(width_tmp, height_tmp);
    return (int)(size/MAXIMUM_SIZE);
}

For a faster decoding of the bitmap it is indicated that the scale used to set o.inSampleSize to be a power of 2, so you can change getScale() method as follows:

 
private int getScale(int width_tmp, int height_tmp) {
    int scale=1;
    while(true){
        if(width_tmp/2<MAXIMUM_SIZE || height_tmp/2<MAXIMUM_SIZE)
            break;
        width_tmp/=2;
        height_tmp/=2;
        scale++;
    }
}

Happy coding,
Bogdan

||||| 0 I Like It! |||||

Hi, for today I choose to show you how to get and display all the images from SD card.

For this we’ll create an activity SDImagesGallery (the gallery), and an adapter GalleryAdapter (the adapter for the gallery).

1. Let’s begin with the xml layout for the SDImageGallery activity:

gallery_layout.xml

 
<?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:orientation="vertical" >
 
    <ImageView android:id="@+id/image_view_gallery" 
        android:layout_width="match_parent" 
	android:layout_height="match_parent"
	android:contentDescription="@string/gallery"/>
 
    <Gallery 
	android:id="@+id/gallery" 
	android:layout_width="match_parent"
	android:layout_height="wrap_content"
	android:layout_weight="0"/>
 
</LinearLayout>

2. Create SDImageGallery activity as follows:
(Important: In order not to block the UI thread we’ll use an AsyncTask class to get the images)

 
import java.util.ArrayList;
 
import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.Toast;
 
 
public class GalleryActivity extends Activity {
 
	private Gallery mGallery;
	private ImageView mImageView;
	private ProgressDialog mProgressDialog;
	private ArrayList<String> mImages = new ArrayList<String>();
	private int currentIndex;
	private GetImagesAsync getImagesAsync; 
 
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.gallery_layout);
 
		mGallery = (Gallery) findViewById(R.id.gallery);
		mImageView = (ImageView) findViewById(R.id.image_view_gallery);
 
		GalleryAdapter adapter = new GalleryAdapter(this);
		mGallery.setAdapter(adapter);
 
		mImageView.setImageResource(0);
 
		setViews();	
 
		getImagesAsync = new GetImagesAsync();
		getImagesAsync.execute((Void) null);
	}
 
	public void setView() {
		mGallery.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				mImageView.setImageURI(Uri.parse(mImages.get(arg2)));
			}
		});
 
		mGallery.setCallbackDuringFling(false);		
		mGallery.setOnItemSelectedListener(new OnItemSelectedListener() {
 
			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				mImageView.setImageURI(Uri.parse(mImages.get(arg2)));
			}
 
			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub
			}
 
		});
	}
 
	public class GetImagesAsync extends AsyncTask<Void, Void, Boolean> {
		@Override
		protected void onPreExecute() {
			mProgressDialog = ProgressDialog.show(ImageAlbums.this,
					null, "Loading images...", true, false);
		}
 
		@Override 
		protected Boolean doInBackground(Void...voids) {
			result = getImages();
 
			return result;
		}
 
		@Override
		protected void onPostExecute(Boolean result) {
			mProgressDialog.dismiss();
			if(result) {
				adapter.setData(mImages);
				adapter.notifyDataSetChanged();	
			}else {
				Toast.makeText(SDImageGallery.this, "No SD card available", Toast.LENGTH_LONG).show();
			}
		}
	}
 
	private boolean getImages() {
 
		if(!isSdAvailable()){
			return false;
		}
 
		String[] projection = {MediaStore.Images.Media.DATA};
		String ord = MediaStore.Images.Media.DATA;
 
		ContentResolver cr = getContentResolver();
		Cursor mCursor = cr.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, 
  				projection, 
  				null, 
  				null, 
  				ord + " ASC");	
 
  		if (mCursor != null && mCursor.moveToFirst()) 
  		{
			while(!mCursor.isAfterLast())
			{
	        		String data = mCursor.getString(mCursor.getColumnIndexOrThrow(ord));
	        		mImages.add(data);
	        		mCursor.moveToNext();
			}
			mCursor.close();
  		}
 
  		return true;
 
	}
 
	private boolean isSdAvailable()
	{
		boolean state = android.os.Environment.getExternalStorageState().equals(
				android.os.Environment.MEDIA_MOUNTED);
		return state;
	}
 
}

3. Create an adapter for the gallery:

 
import android.content.Context;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
 
import java.util.ArrayList;
 
public class GalleryAdapter extends BaseAdapter{
 
	Context mContext;
	int mGalleryItemBackground;
	ArrayList<String> mImages = new ArrayList<String>();
	Resources resources;
 
	public GalleryAdapter(Context context) {
		mContext = context;
		TypedArray a = mContext.obtainStyledAttributes(R.styleable.Gallery1);
        	mGalleryItemBackground = a.getResourceId(R.styleable.Gallery1_android_galleryItemBackground, 0);
        	a.recycle();
        	resources = context.getResources();
	}
 
	@Override
	public int getCount() {
		return mImages.size();
	}
 
	@Override
	public String getItem(int index) {
		return mImages.get(index);
	}
 
	@Override
	public long getItemId(int id) {
		return id;
	}
 
	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		ImageView i = new ImageView(mContext);
 
		i.setImageURI(Uri.parse(mImages.get(position)));
		i.setLayoutParams(new Gallery.LayoutParams(resources.getDimension(R.dimen.mThumbnailWidth), resources.getDimension(R.dimen.mThumbnailHeight)));
		i.setBackgroundResource(mGalleryItemBackground);
 
    		return i;
	}
 
	public void setData(ArrayList<String> images) {
		mImages.addAll(images);
	}
 
	public void clearData() {
		mImages.clear();
	}
}

R.dimen.mThumbnailWidth and R.dimen.mThumbnailHeight can be defined in res/values/dimens.xml as follows:

 
<resources>
 
    <dimen name="mThumbnailWidth">120dp</dimen>
    <dimen name="mThumbnailHeight">68dp</dimen>
 
</resources>

Happy coding,
Bogdan

||||| 1 I Like It! |||||

Hi.
Once again, this is Bogdan with another article for androidgenuine.com.

Today I will show you a simple but very usefull thing. I will show you how to start anactivityforresult to the camera and how the taken photo will be transformed into a bitmap a seen on an imageview.

The tutorial is simple and pretty short. I have only one class : ImageCapture.class and an xml file : mylayout.xml (like usual, I am too lazy to change the name of the layout).

Here is the Java code for ImageCapture class:

public class ImageCapture extends Activity implements View.OnClickListener{	
	//The declaration part...
	Button b;
	ImageView iv;
	final static int cameraData = 0;
	Bitmap  bmp;
 
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.mylayout);
		//We call for initialize method
		initialize();
		//We use the inputstream to get the drawable resource
		InputStream is = getResources().openRawResource(R.drawable.ic_launcher);
		bmp = BitmapFactory.decodeStream(is);
	}
	private void initialize() {
		// TODO Auto-generated method stub
		//Stuff with imageview and button, I suppose you know these.
		iv = (ImageView) findViewById(R.id.ivReturnedPic);
		b = (Button) findViewById (R.id.bTakePic);
 
		b.setOnClickListener(this);
	}
	 public void onClick(View v) {
		// TODO Auto-generated method stub
 
		 //Here is the intent that we use to start the Camera
			Intent i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
			//Here we start the activity for result with the unique code "cameraData" and intent i.
			startActivityForResult(i, cameraData);
	}
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		//Check the unique code if it matches with the RESULT_OK
		if (resultCode == RESULT_OK){
			//The bundle where we collect the extras
			Bundle extras = data.getExtras();
			// Here is our bitmap - the photo we'd just taken
			bmp = (Bitmap) extras.get("data");
			//Here we set the bitmap to our imageview
			iv.setImageBitmap(bmp);
		}
	}
 
}

And here is the code for the 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:orientation="vertical" >
 
    <ImageView
        android:id="@+id/ivReturnedPic"
        android:layout_width="250dp"
        android:layout_height="250dp"
        android:layout_gravity="center"
        android:layout_marginTop="20dip"
        android:src="@drawable/ic_launcher" />
 
 
 
    <Button
        android:layout_gravity="center"
        android:id="@+id/bTakePic"
        android:layout_width="150dp"
        android:layout_marginTop="10dip"
        android:layout_height="wrap_content"
        android:text="Take picture" />
 
</LinearLayout>

Here is a picture where you can see how the application looks like :

Like always, you can download the entire project from here.

This was all for this tutorial . I hope you enjoyed it and you’ll read my future articles , too. Until next tutorial, bye !

||||| 0 I Like It! |||||

How to change the volume using a seekbar

Hi.
This is Bogdan with another interesting , I hope, tutorial for http://androidgenuine.com .

Today I will show you how to adjust the sound of the mediaplayer using a seekbar. I guess you have at least one song on your phone to check if the change of volume works but in any case I also put in this project 3 buttons : Start , Pause and Stop ; to control the song I added.
I hope you do not dislike the song so much. Anyway, I like this song so that’s why it is Maroon 5 – Moves Like Jagger.

Ok. The structure is simple :
-I have a class called: ControlVolume.class
-An xml file : mylayout.xml (like usual)
-This is important .Be focused. I created a new folder in type resources (res) called raw where I added the song.

Here is ControlVolume.class:

public class ControlVolume extends Activity implements OnSeekBarChangeListener{   //We neww onseekbarchangelistener so I implemented it
 
	//Here I declare some stuff
 
	private static TextView reading = null;
	AudioManager audioManager;
	  MediaPlayer oSong;
	  int stopped =1 ;
	    @Override
 
	    public void onCreate(Bundle savedInstanceState) {
	        super.onCreate(savedInstanceState);
	        setContentView(R.layout.mylayout); //The layout that we are using
 
	        //Here is a song that I have in a folder that I create in resources.
	        //The name of the folder is raw and there is my song called "melodie"
	        //Actually the song is Maroon 5 - Moves Like Jaggar
			oSong = MediaPlayer.create(ControlVolume.this, R.raw.melodie);
			//Here is the textview that we are using to show to progress : ?%
			reading = (TextView) findViewById(R.id.reading);
	        SeekBar seekBar = (SeekBar) findViewById(R.id.sbSound);
	        //Here we declare the audioManager . We change the volume with it.
	        audioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
	        //We need the stream max volume to set the seekbar's maximum with this value
	        int maxV = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
	        //We want that the default progress of the seekbar to be the value that the sound is in that moment.
	        //For example if the sound is 50%  we want the progress of the seekbar to be at the half of it
			int curV = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
			//Here we set the max and progress like I said above.
			seekBar.setMax(maxV);
			seekBar.setProgress(curV);
			//Here we do some maths to find out the percentage of the volume and the seekbar's progress is.
			int x = (int)(curV*(((float)100/15)));
			//We set the default text for our textview
			reading.setText(""+x+"% ");
			//Here we have the 3 buttons : Start,Pause,Stop; for our song.
			Button bStart = (Button) findViewById(R.id.bStart);
			bStart.setOnClickListener(new View.OnClickListener() {
 
				public void onClick(View arg0) {
					// TODO Auto-generated method stub
					//I am using the int stopped to know if the song is stopped or paused
 
					if(stopped==1){
						//If it is stopped we need to assign it the song we want again.
					oSong = MediaPlayer.create(ControlVolume.this, R.raw.melodie);
					}
					oSong.start();
 
				}
			});	
			Button bPause = (Button) findViewById(R.id.bPause);
			bPause.setOnClickListener(new View.OnClickListener() {
 
				public void onClick(View arg0) {
					// TODO Auto-generated method stub
					oSong.pause();
					//Playing with stopped variable
					stopped=0;
				}
			});	
			Button bStop = (Button) findViewById(R.id.bStop);
			bStop.setOnClickListener(new View.OnClickListener() {
 
				public void onClick(View arg0) {
					// TODO Auto-generated method stub
					oSong.stop();
					stopped=1;
				}
			});	
 
 
	   //We set the onseekbarchangelistener
	        seekBar.setOnSeekBarChangeListener(this);
	        }
		public void onProgressChanged(SeekBar arg0, int progress, boolean arg2) {
			// TODO Auto-generated method stub
			//We update the textview with actual progress
			int x = (int)(progress*(((float)100/15)));
			reading.setText(""+x+"% ");
			//We update the sound with actual progress of the seekbar
			audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, progress, 0);
		}
		public void onStartTrackingTouch(SeekBar arg0) {
			// TODO Auto-generated method stub
 
		}
		public void onStopTrackingTouch(SeekBar arg0) {
			// TODO Auto-generated method stub
 
		}
 
	}

Here is the 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:orientation="vertical"
    android:padding="20dp">
 
 
    <LinearLayout 
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:layout_gravity="center"
    >
 
        <Button
            android:id="@+id/bStart"
            android:layout_width="80dip"
            android:layout_height="wrap_content"
            android:text="Start" />
 
         <Button
            android:id="@+id/bPause"
            android:layout_width="80dip"
            android:layout_height="wrap_content"
            android:text="Pause" />
         <Button
            android:id="@+id/bStop"
            android:layout_width="80dip"
            android:layout_height="wrap_content"
            android:text="Stop" />
 
        </LinearLayout>
    <SeekBar
        android:id="@+id/sbSound"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
 
         />
 
	<TextView 
	    android:id="@+id/reading"
	    android:text="0%"
	    android:layout_width="wrap_content"
	    android:layout_height="wrap_content"
	    android:textSize="40dp"
	    android:layout_gravity="center"
 
	    />
 
</LinearLayout>

Here is a picture where you can see how the application looks like:

You can download the entire project, like always, from here.

This was all for this tutorial. I hope you understood and liked it. See you with more new and interesting stuff . Bye!

||||| 0 I Like It! |||||

Play a .pls file in Android.

Ok , I suppose most of you know that to listen to a radio station from Shoutcast you need to play a .pls file.
If you download the .pls file on your Android phone and you’ll try to play it you’ll notice that you can’t do that.
So, in this tutorial I’ll teach you how to play a .pls file in an Android application.

Like always, I made a short sample which you’ll be able to download .I’ll explain you step by step by adding comments in the Java code. In this project I created only a class and an XML file.

Ok. Here is the ListenToTheRadio.class :

public class ListenToTheRadio extends Activity{
 
MediaPlayer mp; //We declare the mediaplayer
Button bStart,bPause,bStop; //We declare the buttons we will use
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.mylayout);
 
mp = new MediaPlayer();
 
bStart = (Button) findViewById(R.id.bStart); //findviewbyid for this 3 buttons
bPause = (Button) findViewById(R.id.bPause);
bStop = (Button) findViewById(R.id.bStop);
 
bStart.setOnClickListener(new View.OnClickListener() { //Ok this is the most importat part, be focused !
 
public void onClick(View v) { //This happens when we click the Start button.
// TODO Auto-generated method stub
 
/* Ok, let me explain what this "if" does. The mediaplayer can be stopped or paused. If it is paused with
mp.start(); we can resume it but if it is stopped we need to setDataSource and prepare it again(to get data from the link).
So, I made as when we click the start button , it will unclickable but when you click pause or stop it will be clickable.
If this is foggy for you I think you will understand more as you read the code.
*/
if(bStop.isClickable()){
 
mp.start(); //Here we resume after we pressed the Pause button.
 
}else{
 
try {
mp.setDataSource("http://92.114.63.16:8100/"); //Here we set the source
//As you see, you need to enter the link to the shoutcast radio.
//DO NOT write /listen.pls also, write ONLY the link
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) { //This try and catch we need to put them because if we don't
//will have errors.
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
mp.prepare(); //We prepare the mediaplayer to run.
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace(); //Another some boring try and catch clauses.
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
 
mp.start(); //Here we DO NOT resume, we START the MediaPlayer.
 
//Here we set the clickable value for the 3 buttons
bStart.setClickable(false);
bPause.setClickable(true);
bStop.setClickable(true);
}
}
});
 
bPause.setOnClickListener(new View.OnClickListener() {
 
public void onClick(View v) {
// TODO Auto-generated method stub
mp.pause(); //We pause the MediaPlayer
 
//Start button will be clickable, as well as the Stop button but the Pause button will be unclickable
bStart.setClickable(true);
bPause.setClickable(false);
bStop.setClickable(true);
}
});
 
bStop.setOnClickListener(new View.OnClickListener() {
 
public void onClick(View v) {
// TODO Auto-generated method stub
mp.stop(); //Here we stop the MediaPlayer
 
//Another change for the buttons clickable's values.
bStop.setClickable(false);
bPause.setClickable(false);
bStart.setClickable(true);
}
});
 
bPause.setClickable(false);
bStop.setClickable(false); //At first we will be able to click only on the start Button
 
}
}

Here is the mylayout.xml file where we have the three buttons :

<?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:orientation="horizontal" >
 
    <Button
        android:id="@+id/bStart"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Start" />
 
    <Button
        android:id="@+id/bPause"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Pause" />
 
    <Button
        android:id="@+id/bStop"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Stop" />
 
</LinearLayout>

VERY IMPORTANT !
In your Manifest file please enter the Internet Permission :

<uses-permission android:name="android.permission.INTERNET"/>

You can download the entire project from here .

This is all for this tutorial. Thank you for reading and I hope you enjoyed it.

||||| 0 I Like It! |||||

Hi,
I want to show you here a complete tutorial of making a videorecorder. I just browsed all over the internet, but there is not a fully working code that can record full HD videos or any type of videos.
I faced many issues, like samsung galaxy which dont support full hd resolutions, or the image was green, or some flickeering. This code will fix all this issues.
I hope this will help you.
Code for VideoRecorderActivity:

package com.androidgenuine.videorecorder;
 
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import android.app.Activity;
import android.hardware.Camera;
import android.hardware.Camera.Size;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.Toast;
 
public class VideoRecorderActivity extends Activity implements
		Camera.ErrorCallback, SurfaceHolder.Callback, OnClickListener {
 
	private static final String TAG = "VideoRecording";
 
	Handler handler = new Handler();
	private Camera mCamera;
	private CameraPreview mPreview;
	private MediaRecorder mMediaRecorder;
	private Button captureButton;
	private boolean isRecording = false;
	private List<Size> sizes;
 
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		// Create an instance of Camera.
		if (mCamera == null) {
			mCamera = getCameraInstance();
			// Create preview view and set it as the content of our activity.
			mPreview = new CameraPreview(this, mCamera);
		} else {
			mCamera.release();
			mCamera = getCameraInstance();
			// Create preview view and set it as the content of our activity.
			mPreview = new CameraPreview(this, mCamera);
 
		}
		int i = R.id.videoview;
		Object o = this.findViewById(i);
		FrameLayout preview = (FrameLayout) o;
		preview.addView(mPreview);
 
		Camera.Parameters params = mCamera.getParameters();
		params.set("cam_mode", 1);
		mCamera.setParameters(params);
 
		sizes = params.getSupportedPreviewSizes();
 
		// Add a listener to the Capture button
		captureButton = (Button) findViewById(R.id.mybutton);
		captureButton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				if (isRecording) {
					mMediaRecorder.stop();
					// TODO Auto-generated method stub
 
					// stop recording and release camera
					// stop the recording
					releaseMediaRecorder(); // release the MediaRecorder object
					mCamera.lock(); // take camera access back from
									// MediaRecorder
					// inform the user that recording has stopped
					setCaptureButtonText("Capture");
					isRecording = false;
				} else {
 
					// initialize video camera
					if (prepareVideoRecorder()) {
						// Camera is available and unlocked, MediaRecorder is
						// prepared,
						// now you can start recording
 
						mMediaRecorder.start();
						// inform the user that recording has started
						setCaptureButtonText("Stop");
 
						isRecording = true;
					} else {
						// prepare didn't work, release the camera
						releaseMediaRecorder();
 
					}
				}
			}
		});
	}
 
	public void setCaptureButtonText(String s) {
		captureButton.setText(s);
	}
 
	@Override
	public void surfaceCreated(SurfaceHolder holder) {
		// The Surface has been created, now tell the camera where to draw the
		// preview.
		try {
			mCamera.setPreviewDisplay(holder);
			mCamera.startPreview();
 
		} catch (IOException e) {
			Log.d(TAG, "Error setting camera preview: " + e.getMessage());
			Toast.makeText(this, "Device is not supported!", Toast.LENGTH_LONG)
					.show();
		}
	}
 
	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width,
			int height) {
		// TODO Auto-generated method stub
	}
 
	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {
		// TODO Auto-generated method stub
	}
 
	private boolean prepareVideoRecorder() {
		// mCamera = getCameraInstance();
		mMediaRecorder = new MediaRecorder();
		// Step 1: Unlock and set camera to MediaRecorder
		mCamera.unlock();
		mMediaRecorder.setCamera(mCamera);
		// Step 2: Set sources
		// activate this for recording with sound
		// mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
		mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
 
		mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
 
		mMediaRecorder.setVideoSize(getMaxSupportedVideoSize().width,
				getMaxSupportedVideoSize().height);
		mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
		// mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);//
		// activate this for recording with sound
 
		// Step 4: Set output file
		mMediaRecorder.setOutputFile(getOutputMediaFile("movie"));
		// Step 5: Set the preview output
		mMediaRecorder.setPreviewDisplay(mPreview.getHolder().getSurface());
		// Step 6: Prepare configured MediaRecorder
		try {
			mMediaRecorder.prepare();
		} catch (IllegalStateException e) {
			Log.d(TAG,
					"IllegalStateException preparing MediaRecorder: "
							+ e.getMessage());
			Toast.makeText(this, "Device is not supported!", Toast.LENGTH_LONG)
					.show();
			releaseMediaRecorder();
			return false;
		} catch (IOException e) {
			Log.d(TAG, "IOException preparing MediaRecorder: " + e.getMessage());
			Toast.makeText(this, "Device is not supported!", Toast.LENGTH_LONG)
					.show();
			releaseMediaRecorder();
			return false;
		}
		return true;
	}
 
	@Override
	public void onClick(View v) {
		/*
		 * Log.i("onClick", "BEGIN"); if(!recording) { recording =
		 * startRecording(); } else { stopRecording(); recording = false; }
		 * Log.i("onClick", "END");
		 */
	}
 
	@Override
	protected void onPause() {
		super.onPause();
		if (isRecording) {
			mMediaRecorder.stop();
			releaseMediaRecorder();
			mCamera.lock();
			setCaptureButtonText("RECORD");
			isRecording = false;
		} else {
			releaseMediaRecorder();
		}
		// releaseCamera();
 
	}
 
	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (isRecording) {
			mMediaRecorder.stop();
			releaseMediaRecorder();
			mCamera.lock();
			setCaptureButtonText("RECORD");
			isRecording = false;
		} else {
			releaseMediaRecorder();
			releaseCamera();
		}
		// releaseCamera();
 
	}
 
	private void releaseMediaRecorder() {
		if (mMediaRecorder != null) {
			mMediaRecorder.reset(); // clear recorder configuration
			mMediaRecorder.release(); // release the recorder object
			mMediaRecorder = null;
			mCamera.lock(); // lock camera for later use
		}
	}
 
	private void releaseCamera() {
		if (mCamera != null) {
			mCamera.release(); // release the camera for other applications
			mCamera = null;
		}
	}
 
	private Camera getCameraInstance() {
		Camera c = null;
		try {
			c = Camera.open(); // attempt to get a Camera instance
			// c = this.open(); // attempt to get a Camera instance
		} catch (Exception e) {
			// Camera is not available (in use or does not exist)
		}
		return c; // returns null if camera is unavailable
	}
 
	public Camera open() {
		return Camera.open();
	}
 
	@Override
	public void onError(int error, Camera camera) {
		// TODO Auto-generated method stub
		if (error == Camera.CAMERA_ERROR_SERVER_DIED
				|| error == Camera.CAMERA_ERROR_UNKNOWN) {
			releaseCamera();
			finish();
			Toast.makeText(this, "Camera has died", Toast.LENGTH_LONG).show();
		}
	}
 
	public Size getMaxSupportedVideoSize() {
		int maximum = sizes.get(0).width;
		int position = 0;
		for (int i = 0; i < sizes.size() - 1; i++) {
			if (sizes.get(i).width > maximum) {
				maximum = sizes.get(i).width; // new maximum
				position = i - 1;
			}
		}
		if (position == 0) {
			int secondMax = sizes.get(1).width;
			position = 1;
			for (int j = 1; j < sizes.size() - 1; j++) {
				if (sizes.get(j).width > secondMax) {
					secondMax = sizes.get(j).width; // new maximum
					position = j;
				}
 
			}
		}
 
		return sizes.get(position);
		// end method max
 
	}
 
	private static String getOutputMediaFile(String sufix) {
 
		String mediaFile;
		File mediaStorageDir = new File(
				Environment.getExternalStorageDirectory(), "/VideoLogger");
		if (!mediaStorageDir.exists()) {
			if (!mediaStorageDir.mkdirs()) {
				Log.d("VideoLogger", "failed to create directory");
				return null;
			}
		}
		String timeStamp = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss")
				.format(new Date());
		if (!sufix.equals("movie")) {
			mediaFile = mediaStorageDir.getPath() + File.separator + "output_"
					+ timeStamp + "_" + sufix + ".txt";
		} else {
			mediaFile = mediaStorageDir.getPath() + File.separator + "output_"
					+ timeStamp + ".mp4";
 
		}
 
		return mediaFile;
	}
}

Code for main.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"
    android:orientation="vertical" >
 
    <FrameLayout
        android:id="@+id/videoview"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" />
 
 
    <Button
        android:id="@+id/mybutton"
        android:layout_width="150dip"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:text="RECORD"
        android:textSize="12dp"/>
 
</RelativeLayout>

Code for CameraPreview.java

 
package com.androidgenuine.videorecorder;
 
import java.io.IOException;
import java.util.List;
 
import android.content.Context;
import android.hardware.Camera;
import android.hardware.Camera.Size;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
 
public class CameraPreview extends SurfaceView implements
		SurfaceHolder.Callback {
 
	private SurfaceHolder mHolder;
	private Camera mCamera;
	private List<Size> sizes;
 
	public CameraPreview(Context context, Camera camera) {
		super(context);
		mCamera = camera;
 
		// Install a SurfaceHolder.Callback so we get notified when the
		// underlying surface is created and destroyed.
		mHolder = getHolder();
		mHolder.addCallback(this);
		// deprecated setting, but required on Android versions prior to 3.0
		mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
	}
 
	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width,
			int height) {
		// If your preview can change or rotate, take care of those events here.
		// Make sure to stop the preview before resizing or reformatting it.
 
		if (mHolder.getSurface() == null) {
			// preview surface does not exist
			return;
		}
 
		// stop preview before making changes
		try {
			mCamera.stopPreview();
		} catch (Exception e) {
			// ignore: tried to stop a non-existent preview
		}
 
		// make any resize, rotate or reformatting changes here
		Camera.Parameters params = mCamera.getParameters();
		sizes = params.getSupportedPreviewSizes();
		Log.d("PREVIEW SIZES", String.valueOf(getMaxSupportedVideoSize().width)+":"+String.valueOf(getMaxSupportedVideoSize().height));
		params.setPreviewSize(getMaxSupportedVideoSize().width, getMaxSupportedVideoSize().height);
		mCamera.setParameters(params);
		// start preview with new settings
		try {
 
			mCamera.setPreviewDisplay(mHolder);
			mCamera.startPreview();
 
		} catch (Exception e) {
		}
	}
 
	@Override
	public void surfaceCreated(SurfaceHolder holder) {
		// TODO Auto-generated method stub
		// The Surface has been created, now tell the camera where to draw the
		// preview.
		try {
			mCamera.setPreviewDisplay(holder);
			mCamera.startPreview();
		} catch (IOException e) {
		}
	}
 
	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {
		// TODO Auto-generated method stub
 
	}
 
	public Size getMaxSupportedVideoSize() {
		int maximum = sizes.get(0).width;
		int position = 0;
		for (int i = 0; i < sizes.size() - 1; i++) {
			if (sizes.get(i).width > maximum) {
				maximum = sizes.get(i).width; // new maximum
				position = i - 1;
			}
		}
		if (position == 0) {
			int secondMax = sizes.get(1).width;
			position = 1;
			for (int j = 1; j < sizes.size() - 1; j++) {
				if (sizes.get(j).width > secondMax) {
					secondMax = sizes.get(j).width; // new maximum
					position = j;
				}
 
			}
		}
 
		return sizes.get(position);
		// end method max
 
	}
 
}

The permissions are:

<uses-permission android:name="android.permission.RECORD_VIDEO" />
    <uses-permission android:name="android.permission.CAMERA" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.RECORD_AUDIO" />
 
    <uses-feature android:name="android.hardware.camera" />
    <uses-feature android:name="android.hardware.camera.autofocus" />

Also please use screen orientation landscape in manifest for this to work.
If you have questions please post them in the comment section.

||||| 2 I Like It! |||||

Hi, today i want to put all this stuff in one place, because i never found toghether and correct, this informations.
Mainly, the purpose of this tutorial is to create and set a reminder/alarm on a certain date. This reminder will appear like a notification with sound and vibration, even if we closed the app that setted this reminder/alarm.

In the Main.java class we will set the alarm. I will just show you how to set it, but you need to put this code in a button or somewhere else where you need it.

	Calendar cal = Calendar.getInstance();       //for using this you need to import java.util.Calendar;
 
				// add minutes to the calendar object
				cal.set(Calendar.MONTH, 4);
				cal.set(Calendar.YEAR, 2011);				
				cal.set(Calendar.DAY_OF_MONTH, 5);
				cal.set(Calendar.HOUR_OF_DAY, 21);
				cal.set(Calendar.MINUTE, 43);
//cal.set will set the alarm to trigger exactly at: 21:43, 5 May 2011
//if you want to trigger the alarm after let's say 5 minutes after is activated you need to put
//cal.add(Calendar.MINUTE, 5);
	Intent alarmintent = new Intent(getApplicationContext(), AlarmReceiver.class);
alarmintent.putExtra("title","Title of our Notification");
alarmintent.putExtra("note","Description of our  Notification");
//HELLO_ID is a static variable that must be initialised at the BEGINNING OF CLASS with 1;
 
//example:protected static int HELLO_ID =1;
PendingIntent sender = PendingIntent.getBroadcast(getApplicationContext(), HELLO_ID,
alarmintent,PendingIntent.FLAG_UPDATE_CURRENT|  Intent.FILL_IN_DATA);
//VERY IMPORTANT TO SET FLAG_UPDATE_CURRENT... this will send correct extra's informations to 
//AlarmReceiver Class
				// Get the AlarmManager service
 
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), sender);

Now I will show you AlarmReceiver.java
This class must be declared in Manifest as a receiver because it will extend BroadcastReceiver.
So we put in Manifest before tag the following line:

 <receiver android:name=".AlarmReceiver"></receiver>

Code for AlarmReceiver.java. Please follow comments instructions also.

 
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.widget.Toast;
 
public class AlarmReceiver extends BroadcastReceiver {
 
	private static int NOTIFICATION_ID = 1;
 
	@Override
	public void onReceive(Context context, Intent intent) {
 
	        // NotificationManager mNotificationManager = 
(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
NotificationManager manger = (NotificationManager)     
context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(R.drawable.icon, "Combi Note",
 System.currentTimeMillis());
PendingIntent contentIntent = PendingIntent.getActivity(context, 
NOTIFICATION_ID, 
new Intent(context, AlarmReceiver.class), 0);
		Bundle extras=intent.getExtras();
		String title=extras.getString("title");
//here we get the title and description of our Notification
			//
		String note=extras.getString("note");
		notification.setLatestEventInfo(context, note, title, contentIntent);
		notification.flags = Notification.FLAG_INSISTENT;
		notification.defaults |= Notification.DEFAULT_SOUND;
//here we set the default sound for our 
//notification
 
		// The PendingIntent to launch our activity if the user selects this notification
		manger.notify(NOTIFICATION_ID++, notification);
 
 
 
	}
 
};

I hope i make it clear and simple how you can set a notification that can be a reminder or an alarm that will be activated even if we closed the app or processes.

||||| 3 I Like It! |||||

How to use ContextMenu on a listView

Hi,
I will show you how you can create a contextmenu for your listview.
What is a contextMenu? A contextMenu is something like “right click”, only that on smartphones you need to
longclick to trigger a ContextMenu. So, this will trigger additional options to a listview item.
Let’s say this is an ListActivity:

 
public class Main extends ListActivity{
@Override
public void OnCreate(Bundle savedInstanceState){
super.OnCreate(savedInstanceState);
setContentView(R.layout.main);
ListView mylist=getListView();
//below we declare our contextMenu, and we add 2 options that we can click on LongClick
 
myList.setOnCreateContextMenuListener(new OnCreateContextMenuListener() {
 
 
		@Override
		public void onCreateContextMenu(ContextMenu arg0, View arg1,
				ContextMenuInfo arg2) { 
 
			// TODO Auto-generated method stub
			arg0.setHeaderTitle(" Menu: ");//contextmenu
			arg0.add(0, 0,0, "Edit!");
		       	arg0.add(0, 1,0, "Delete!");
}
		});
}
//after this, we override the follwing method
 @Override
	 public boolean onContextItemSelected(MenuItem aItem) {
	 AdapterContextMenuInfo menuInfo = (AdapterContextMenuInfo) aItem.getMenuInfo();
	 /* Switch on the ID of the item, to get what the user selected. */
 
 
	 switch (aItem.getItemId()) {
	 case 0:
//do something	
 return true; /* true means: “we handled the event”. */
	 case 1:
//do somethingelse
return true;
}
	 return false;
	 }
 
}//close the class...
||||| 0 I Like It! |||||

Search

Popular

Sponsors