Thursday 21 June 2012

Voice Recording in Android

Put below code into your main Activity.

private static final String AUDIO_RECORDER_FILE_EXT_3GP = ".3gp";
private static final String AUDIO_RECORDER_FILE_EXT_MP4 = ".mp4";
private static final String AUDIO_RECORDER_FOLDER = "AudioRecorder";
private MediaRecorder recorder = null;
private int currentFormat = 0;
private int output_formats[] = { MediaRecorder.OutputFormat.MPEG_4, MediaRecorder.OutputFormat.THREE_GPP };
private String file_exts[] = { AUDIO_RECORDER_FILE_EXT_MP4, AUDIO_RECORDER_FILE_EXT_3GP };

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
setButtonHandlers();
enableButtons(false);
setFormatButtonCaption();
}

private void setButtonHandlers() {
    ((Button) findViewById(R.id.btnStart)).setOnClickListener(btnClick);
((Button) findViewById(R.id.btnStop)).setOnClickListener(btnClick);
((Button) findViewById(R.id.btnFormat)).setOnClickListener(btnClick);
}

private void enableButton(int id, boolean isEnable) {
((Button) findViewById(id)).setEnabled(isEnable);
}

private void enableButtons(boolean isRecording) {
enableButton(R.id.btnStart, !isRecording);
enableButton(R.id.btnFormat, !isRecording);
enableButton(R.id.btnStop, isRecording);
}

private void setFormatButtonCaption() {
((Button) findViewById(R.id.btnFormat)).setText(getString(R.string.audio_format) + " (" + file_exts[currentFormat] + ")");
}

private String getFilename() {
String filepath = Environment.getExternalStorageDirectory().getPath();
File file = new File(filepath, AUDIO_RECORDER_FOLDER);
if (!file.exists()) {
file.mkdirs();
}
return (file.getAbsolutePath() + "/" + System.currentTimeMillis() + file_exts[currentFormat]);
}

private void startRecording() {
recorder = new MediaRecorder();
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setOutputFormat(output_formats[currentFormat]);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
recorder.setOutputFile(getFilename());
recorder.setOnErrorListener(errorListener);
recorder.setOnInfoListener(infoListener);
try {
recorder.prepare();
recorder.start();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

private void stopRecording() {
  if (null != recorder) {
recorder.stop();
recorder.reset();
recorder.release();
recorder = null;
}
}

private void displayFormatDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
String formats[] = { "MPEG 4", "3GPP" };
builder.setTitle(getString(R.string.choose_format_title)).setSingleChoiceItems(formats, currentFormat, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
currentFormat = which;
setFormatButtonCaption();
dialog.dismiss();
}
}).show();
}

private MediaRecorder.OnErrorListener errorListener = new MediaRecorder.OnErrorListener() {
  @Override
public void onError(MediaRecorder mr, int what, int extra) {
Toast.makeText(AudioRecordingActivity.this, "Error: " + what + ", " + extra, Toast.LENGTH_SHORT).show();
    }
};

private MediaRecorder.OnInfoListener infoListener = new MediaRecorder.OnInfoListener() {
@Override
public void onInfo(MediaRecorder mr, int what, int extra) {
Toast.makeText(AudioRecordingActivity.this, "Warning: " + what + ", " + extra, Toast.LENGTH_SHORT).show();
}
};

private View.OnClickListener btnClick = new View.OnClickListener() {
@Override
public void onClick(View v) {
        switch (v.getId()) {
          case R.id.btnStart: {
             Toast.makeText(AudioRecordingActivity.this, "Start Recording", Toast.LENGTH_SHORT).show();
                enableButtons(true);
             startRecording();
             break;
          }
          case R.id.btnStop: {
             Toast.makeText(AudioRecordingActivity.this, "Stop Recording", Toast.LENGTH_SHORT).show();
             enableButtons(false);
             stopRecording();
             break;
          }
          case R.id.btnFormat: {
             displayFormatDialog();
             break;
          }
       }
    }
};


Main.xml File:-


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="20dip">
 
    <ImageView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_launcher"
        android:scaleType="fitCenter"/>
 
        <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/app_info"
        android:layout_weight="1.0"
        android:textSize="20dip"/>
     
    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content">
     
        <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/btnStart"
                android:text="@string/start_recording"
                android:layout_weight="1.0"/>
             
                <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/btnStop"
                android:text="@string/stop_recording"
                android:layout_weight="1.0"/>
             
        <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/btnFormat"
                android:text="Format (mp4)"
                android:layout_weight="1.0"/>
     
    </LinearLayout>
</LinearLayout>


Add Below Permissions to manifest.xml file.

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

Download Full Source Code from below link.

Voice Recording in Android

Don’t forget to provide feedback or follow this blog, if you find this blog is useful.

Play Online Video in Android Device

Put Below Code into your Application.

MainActivity.java File:-

public class MainActivity extends Activity {
public static String url = "rtsp://v3.cache8.c.youtube.com/CiILENy73wIaGQmXovF6e-Rf-BMYDSANFEgGUgZ2aWRlb3MM/0/0/0/video.3gp";
private VideoView videoView = null;
private ProgressBar prog = null;
private Context ctx = null;
private MediaController mediaController = null;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
getWindow().setFormat(PixelFormat.TRANSLUCENT);
setContentView(R.layout.main);
ctx = this;
prog = (ProgressBar) findViewById(R.id.prog);
videoView = (VideoView) findViewById(R.id.video);
Uri video = Uri.parse(url);
mediaController = new MediaController(this);
  mediaController.setAnchorView(videoView);
videoView.setMediaController(mediaController);
videoView.setVideoURI(video);

videoView.setOnErrorListener(new OnErrorListener() {

@Override
public boolean onError(MediaPlayer mp, int what, int extra) {
// TODO Auto-generated method stub
Toast.makeText(ctx, "Error occured", 500).show();
return false;
}
});

videoView.setOnPreparedListener(new OnPreparedListener() {

public void onPrepared(MediaPlayer arg0) {
prog.setVisibility(View.GONE);
videoView.start();
}
});
}

@Override
protected void onDestroy() {
try {
videoView.stopPlayback();
} catch (Exception e) {
//
}
super.onDestroy();
}
}


Main.xml File:-

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <FrameLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" >

        <VideoView
            android:id="@+id/video"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_gravity="center" />

        <ProgressBar
            android:id="@+id/prog"
            android:layout_width="70dp"
            android:layout_height="70dp"
            android:layout_gravity="center" />
    </FrameLayout>

</LinearLayout>


And Give Below Permission into your Manifest.xml file.

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

Enjoy:--)

Don’t forget to provide feedback or follow this blog, if you find this blog is useful.

Tuesday 19 June 2012

How to get Browser History in Android?

Call below function.

public void getBrowserHist()  {
        Cursor mCur = managedQuery(Browser.BOOKMARKS_URI,
                Browser.HISTORY_PROJECTION, null, null, null);
        mCur.moveToFirst();
        if (mCur.moveToFirst() && mCur.getCount() > 0) {
            while (mCur.isAfterLast() == false) {
                Log.v("titleIdx", mCur
                        .getString(Browser.HISTORY_PROJECTION_TITLE_INDEX));
                Log.v("urlIdx", mCur
                        .getString(Browser.HISTORY_PROJECTION_URL_INDEX));
                mCur.moveToNext();
           }
      }
}


Add below uses-permission into your manifest file.

<uses-permission android:name="com.android.browser.permission.READ_HISTORY_BOOKMARKS"/>

Enjoy :-)

Don’t forget to provide feedback or follow this blog, if you find this blog is useful.

Monday 18 June 2012

Convert Bitmap into ByteArray


Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.abstrakt);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();


Enjoy:--)

Don’t forget to provide feedback or follow this blog, if you find this blog is useful.

Saturday 9 June 2012

Delete All Call log in Android

Write Below Line into your Button on Click Event.

this.getContentResolver().delete(CallLog.Calls.CONTENT_URI, null, null);


And Give Below Permission into your Android manifest.XML file.

<uses-permission android:name="android.permission.READ_CONTACTS"/>
<uses-permission android:name="android.permission.READ_LOGS"/>
<uses-permission android:name="android.permission.WRITE_CONTACTS"/>


Enjoy :-)

Don’t forget to provide feedback or follow this blog, if you find this blog is useful.

Thursday 7 June 2012

Integrate Paypal in Android Application

First Create New Android Project and then Add below Code.

MainActivity.java

public class PizzaMain extends Activity implements OnClickListener {
  /** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

PayPal ppObj = PayPal.initWithAppID(this.getBaseContext(), "APP-80W284485P519543T", PayPal.ENV_NONE);

CheckoutButton launchPayPalButton = ppObj.getCheckoutButton(this, PayPal.BUTTON_152x33, CheckoutButton.TEXT_PAY);
  RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);

  params.addRule(RelativeLayout.CENTER_HORIZONTAL);

launchPayPalButton.setLayoutParams(params);
launchPayPalButton.setOnClickListener(this);

((RelativeLayout) findViewById(R.id.mRlayout1)).addView(launchPayPalButton);
    }

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
PayPalPayment newPayment = new PayPalPayment();
char val[] = { '5', '0' };
BigDecimal obj_0 = new BigDecimal(val);
newPayment.setSubtotal(obj_0);
newPayment.setCurrencyType("USD");
newPayment.setRecipient("my@email.com");
newPayment.setMerchantName("My Company");
Intent paypalIntent = PayPal.getInstance().checkout(newPayment, this);
this.startActivityForResult(paypalIntent, 1);
}

@SuppressWarnings("unused")
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (resultCode) {
case Activity.RESULT_OK:
// The payment succeeded
String payKey = data.getStringExtra(PayPalActivity.EXTRA_PAY_KEY);
// Tell the user their payment succeeded
break;
case Activity.RESULT_CANCELED:
// The payment was canceled
// Tell the user their payment was canceled
break;
case PayPalActivity.RESULT_FAILURE:
// The payment failed -- we get the error from the EXTRA_ERROR_ID
// and EXTRA_ERROR_MESSAGE
String errorID = data.getStringExtra(PayPalActivity.EXTRA_ERROR_ID);
String errorMessage = data.getStringExtra(PayPalActivity.EXTRA_ERROR_MESSAGE);
// Tell the user their payment was failed.
               break;
       }
   }
}

And Give below permissions into your AndroidManifest.xml file.

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

And Add Activity into your AndroidManifest.xml file.

<activity
    android:name="com.paypal.android.MEP.PayPalActivity"
    android:configChanges="keyboardHidden|orientation"
    android:theme="@android:style/Theme.Translucent.NoTitleBar" />

Add PayPal_MPL.jar Jar File as a Refrence Library into Your application

Enjoy :-)

Don’t forget to provide feedback or follow this blog, if you find this blog is useful.

Export Contacts as a VCF file in Android


public class VCardActivity extends Activity {
Cursor cursor;
ArrayList<String> vCard;
String vfile;
static Context mContext;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mContext = VCardActivity.this;
getVCF();
}

public static void getVCF() {
final String vfile = "Contacts.vcf";
Cursor phones = mContext.getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
                                  null, null, null);
phones.moveToFirst();
for (int i = 0; i < phones.getCount(); i++) {
String lookupKey = phones.getString(phones
.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
Uri uri = Uri.withAppendedPath(
ContactsContract.Contacts.CONTENT_VCARD_URI,
                                                 lookupKey);
AssetFileDescriptor fd;
try {
fd = mContext.getContentResolver().openAssetFileDescriptor(uri, "r");
FileInputStream fis = fd.createInputStream();
byte[] buf = new byte[(int) fd.getDeclaredLength()];
fis.read(buf);
String VCard = new String(buf);
String path = Environment.getExternalStorageDirectory()
.toString() + File.separator + vfile;
FileOutputStream mFileOutputStream = new FileOutputStream(path,
true);
mFileOutputStream.write(VCard.toString().getBytes());
phones.moveToNext();
Log.d("Vcard", VCard);
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
}

Enjoy :-)

Don’t forget to provide feedback or follow this blog, if you find this blog is useful.