Saturday 24 November 2012

Android Development – Customize Android Fonts

First Create New Android Project and after that add "DroidSansFallback.ttf" file into assets folder.

After that put below code into activity_main.xml file and MainActivity.java file

activity_main.xml


<?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" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Dipak Keshariya"
        android:id="@+id/TextView1" />

</LinearLayout>


MainActivity.java

public class MainActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
     
        // text view label
        TextView mTextView1 = (TextView) findViewById(R.id.TextView1);

        // Loading Font Face
        Typeface tf = Typeface.createFromAsset(getAssets(), "DroidSansFallback.ttf");

        // Applying font
        mTextView1.setTypeface(tf);
    }
}

Download Full Source Code from below link.

Customize Android Fonts

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

Monday 27 August 2012

Multiple Android Activities in a TabActivity

Project Name:- Tab_Sample
Package Name:- com.android.tabsample
Target SDK:- Android 2.2 (API 8)

Create below 5 classes under the "com.android.tabsample" package.

ActivityStack.java


public class ActivityStackHome extends ActivityGroup {
    private Stack<String> stack;

    @Override
    public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (stack == null)
stack = new Stack<String>();
// start default activity
push("FirstStackActivity", new Intent(this, Tab_SampleActivity.class));
    }

    @Override
    public void finishFromChild(Activity child) {
pop();
    }

    @Override
    public void onBackPressed() {
pop();
    }

    public void push(String id, Intent intent) {
  Window window = getLocalActivityManager().startActivity(id, intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
        if (window != null) {
            stack.push(id);
setContentView(window.getDecorView());
}
    }

    public void pop() {
  if (stack.size() == 1)
            finish();
        LocalActivityManager manager = getLocalActivityManager();
  manager.destroyActivity(stack.pop(), true);
if (stack.size() > 0) {
Intent lastIntent = manager.getActivity(stack.peek()).getIntent();
            Window newWindow = manager.startActivity(stack.peek(), lastIntent);
            setContentView(newWindow.getDecorView());
        }
    }
}


TabActivity.java


public class TabActivity extends TabActivity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tab_screen);
TabHost tabHost = getTabHost();
Intent intent = new Intent().setClass(this, ActivityStack.class);
TabHost.TabSpec spec = tabHost.newTabSpec("tabId").setIndicator("Temp", getResources().getDrawable(R.drawable.home));
spec.setContent(intent);

tabHost.addTab(spec);

Intent intent1 = new Intent().setClass(this, ActivityStack.class);
TabHost.TabSpec spec1 = tabHost.newTabSpec("tabId").setIndicator("Temp", getResources().getDrawable(R.drawable.invoice));
spec1.setContent(intent1);
tabHost.addTab(spec1);

tabHost.setCurrentTab(0);
    }
}


FirstActivity.java


public class FirstActivity extends Activity {
  @Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView textView = new TextView(this);
textView.setText("Tab Sample Activity ");
textView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setClass(getParent(), SecondActivity.class);
ActivityStack activityStack = (ActivityStack) getParent();
activityStack.push("SecondActivity", intent);
}
});
 
        setContentView(textView);
  }
}


SecondActivity.java


public class SecondActivity extends Activity {
    @Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView textView = new TextView(this);
textView.setText("First Stack Activity ");
textView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setClass(getParent(), ThirdActivity.class);
ActivityStack activityStack = (ActivityStack) getParent();
activityStack.push("ThirdActivity", intent);
            }
        });
 
        setContentView(textView);
    }
}


ThirdActivity.java


public class ThirdActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
    }
}


Add Below XML files into your res/layout folder.

1) tab_screen.xml


<?xml version="1.0" encoding="utf-8"?>
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/tabhost"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical"
        android:padding="3dp" >

        <FrameLayout
            android:id="@android:id/tabcontent"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_above="@android:id/tabs"
            android:layout_weight="1" />

        <TabWidget
            android:id="@android:id/tabs"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true" />
    </RelativeLayout>

</TabHost>


2) main.xml


<?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" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />

</LinearLayout>


AndroidManifest.xml:-


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.android.tabsample"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="8" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".FirstActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>
        <activity
            android:name=".TabActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".ActivityStack"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>
        <activity
            android:name=".SecondActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>
        <activity
            android:name=".ThirdActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Download Full Source Code from below link.

Android Bottom Tab Example

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

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.

Wednesday 30 May 2012

Android – Send Email Via GMail (Actually Via SMTP)

Create New Android Project and after that add below code into your MainActivity.java and activity_main.xml file.


MainActivity.java

public class MainActivity extends Activity {

  @Override
  protected void onCreate(Bundle savedInstanceState) {
  // TODO Auto-generated method stub
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);

  Button login = (Button) findViewById(R.id.mBtnSubmit);
  login.setOnClickListener(new View.OnClickListener() {

  public void onClick(View arg0) {
  Properties props = new Properties();
  props.put("mail.smtp.host", "smtp.gmail.com");
  props.put("mail.smtp.socketFactory.port", "465");
  props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
  props.put("mail.smtp.auth", "true");
  props.put("mail.smtp.port", "465");

  Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
                    protected PasswordAuthentication getPasswordAuthentication() {
  return new PasswordAuthentication("dipakkeshariya@android.com", "dipakkeshariya");
  }
  });

  try {
  Message message = new MimeMessage(session);
  message.setFrom(new InternetAddress("dipak.keshariya@android.com"));
  message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("dipak.keshariya@mobileappdeveloper.com"));
message.setSubject("Testing Subject");
  message.setContent("Hi Dipak Keshariya (Android Developer)", "text/html; charset=utf-8");

  Transport.send(message);

  } catch (MessagingException e) {
  throw new RuntimeException(e);
  }
            }
  });
    }
}


activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="@string/hello_world" />

    <Button
        android:id="@+id/mBtnSubmit"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="5dip"
        android:text="Send Mail" />

</RelativeLayout>


Download below 3 jar file and add into project's build path.

1) activation.jar
2) additionnal.jar
3) mail.jar

Give Following uses-permission into your Android Manifest file

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

Now Run Your Project.

Enjoy :-)

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

Wednesday 23 May 2012

Simple Notification Example

Put Below Code in onClicklistener( ) event of Button

Timer timer = new Timer();
timer.schedule(new TimerTask() {
    @Override
public void run() {
// Notification Title and Message
Notification("This is message from Dipak Keshariya (Android Application Developer)", "This is Android Notification Message");
}
}, 0);


And write below Method in your MainActivity

private void Notification(String notificationTitle, String notificationMessage) {
    NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    android.app.Notification notification = new android.app.Notification(R.drawable.ic_launcher, "A New Message from Dipak Keshariya (Android Developer)!",
  System.currentTimeMillis());

Intent notificationIntent = new Intent(this, AndroidNotifications.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
    notification.setLatestEventInfo(AndroidNotifications.this, notificationTitle, notificationMessage, pendingIntent);
  notificationManager.notify(10001, notification);
}

And Now Run Your Project.

Enjoy :-)

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

Wednesday 4 January 2012

How to Finish Activity from another View in Android?

Write below code after startactivity(intent) for finish the activity from the view/class.

((Activity_Name1) context).finish();

Enjoy :-----)

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