Search Wikipedia

Search results

Jun 25, 2015

How to Send Email

We  do not need to develop our email client from scratch because they are already available like Gmail and K9mail. But we will need to send email from our android application, where we will have to write an Activity that need to launch an email client and sends an email using our android device. For this purpose, our Acivity will send an ACTION_SEND along with appropriate data load, to the Android Intent Resolver. The specified chooser gives the proper interface for the user to pick how to send our email data.


STEP 1: INTENT OBJECT- Action to send Email


We will use ACTION_SEND action to launch an email client intalled on our Android device.
Following is simple syntax to create an intent with ACTION_SEND action.
Intent emailIntent = new Intent(Intent.ACTION_SEND);

STEP 2: INTENT OBJECT- Data/Type to send Email


To send an email we need to specify mailto: as URI using setData() method and datatype will be tottext/plain using setType() method as follows:
emailItent.setData(Uri.parse("mailto:"));
emailIntent.settype.settype("text/plain");

STEP 3: INTENT OBJECT- Extra to send Email


Android has built-in support to add TO,SUBJECT,CC,TEXT etc. fields which can be attached to intent before sending the intent to target email client.
Here is an example showing how to assign extra data to your intent:
emailIntent. putExtra(Intent.EXTRA_EMAIL,new String[]{"recipent@example.com"});
emailIntent.putExtra(Intent.EXTRA_SUBJECT,"subject of email");
emailIntent.putExtra(Intent.EXTRA_TEXT,"body of email");

Jun 24, 2015

Create and Send Notifications

There is  a simple method  to create notification. Follow the following steps to create a notification.

STEP 1 - CREATE NOTIFICATION BUILDER

As a first step is to create a notification builder using NotificationCompat.Builder.build(). We will use Notification to set various Notification properties like its small and large icons,title,priority etc.
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)

STEP 2 - SETTING NOTIFICATION PROPERTIES

Once we have Builder object, we can set its Notification properties using Builder object as per our requirement. But this is mandatory to set atleast following:
  • A small icon, set by setSmallIcon()
  • A title, set by setContentTitle()
  • Detail text, set by setContentText()
mBuilder.setSmallIcon(R.drawable.notification_icon);
mBuiler.setContentTitle("Notification Alert, Click Me !");
mBuilder.setContentText("Hi, This is Android Notification Detail");

STEP 3 - ATTACH ACTIONS

This is an optional part and required if we want to attach an action with the application. An action allows users to go directly from the notification to an Activity in our application, where user can look at one or more events or do further work.

The action is defined by a PendingIntent containing an Intent that starts an Activity in our application. To asscociate the PendingIntent with a gesture, call the appropriate method of NotificationBuilder.Builder. For example, if we want to start Activity when user clicks the notification text in the notification drawer, you add the PendingIntent by calling setContentIntent().

A PendingIntent object helps us to perform an action on our application's behalf, often at a later time, without caring of whether or  not our application is running.

We can help of stack builder object which will contain an artificial back stack for the started Activity. This ensure the navigating backward from the Activity leads out of our application to the Home screen.

Intent resultIntent = new Intent(this,ResultActivity.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(ResultActivity.class);
//Adds the Intent that starts the Activity to the top of the stack
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,PendingIntent.FLAG_UPDATE_CURRENT);
mbuilder.setCotentIntent(resultPendingIntent);

STEP 4 - ISSUE THE NOTIFICATION

Finally, we can pass the Notification object to the system by calling NotificationManager.notifiy() to send our notification. Make sure we call NotificationCompat.Builder.build() method on builder object before notifying it. This method combines all of the options that have been set and return a new Notification object.

NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
//notificatioID allows us to update the notification later on 
mNotificationManager.notify(notificationID, mBuilder.build());

May 6, 2014

Adjust Screen Brightness in Android with example

Screen Brightness in Android can be controlled programmatically in simple way. This tutorial explains the process with an example. Native brightness control in Android device has a Seekbar that adjust the screen brightness. The below tutorial has UI in a similar way.You take a look at SeekBar tutorial here if needed. 

android.provider.Settings.System - This class contains miscellaneous system preferences. There are convenience functions for accessing individual system settings. android.provider.

Settings.System.getInt - Convenience function for retrieving a single system settings value as an integer. Note that internally setting values are always stored as strings; this function converts the string to an integer for you. The default value will be returned if the setting is not defined or not an integer. 

android.provider.Settings.System.SCREEN_BRIGHTNESS - String that holds Screen Brightness value ranging from 0 to 255.

May 4, 2014

Drawing with Canvas in Android

Before starting this tutorial please check this site https://developer.mozilla.org/enUS/docs/Web/HTML/Canvas/Drawing_graphics_with_canvas and see that you must use paths (2nd example, beginPath) rather than drawing point by point.

On your Activity
private ArrayList _graphics = new ArrayList();
private Paint mPaint;
@Override
public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(new DrawingPanel(this));
  mPaint = new Paint();
  mPaint.setDither(true);
  mPaint.setColor(0xFFFFFF00);
  mPaint.setStyle(Paint.Style.STROKE);
  mPaint.setStrokeJoin(Paint.Join.ROUND);
  mPaint.setStrokeCap(Paint.Cap.ROUND);
  mPaint.setStrokeWidth(3);
  }
On your SurfaceView
@Override
public boolean onTouchEvent(MotionEvent event) {
  synchronized (_thread.getSurfaceHolder()) {
    if(event.getAction() == MotionEvent.ACTION_DOWN){
      path = new Path();
      path.moveTo(event.getX(), event.getY());
      path.lineTo(event.getX(), event.getY());
    }else if(event.getAction() == MotionEvent.ACTION_MOVE){
      path.lineTo(event.getX(), event.getY());
    }else if(event.getAction() == MotionEvent.ACTION_UP){
      path.lineTo(event.getX(), event.getY());
      _graphics.add(path);
    }
    return true;
  }
}
@Override
public void onDraw(Canvas canvas) {
  for (Path path : _graphics) {
    //canvas.drawPoint(graphic.x, graphic.y, mPaint);
    canvas.drawPath(path, mPaint);
  }
}

Explanation

We create a path and start that path when the MotionEvent is down, or when the user first touch the screen, then add a lineTo, the x and y when the user moves his fingers.

Then stop and push the path we had build to our array of Paths.
 public boolean onTouchEvent(MotionEvent event) { .... }

 Then during the draw function we loop through the array and print them on our canvas.
 public void onDraw(Canvas canvas) { ... }

How to Generate random number in Android

Generating Random Number in Android

To generate random number in Android, class java.util.Random can be used.

This class java.util.Random provides methods that generates pseudo-random numbers of different types, such as int, long, double, and float.

It support two public constructor:
Random() - Construct a random generator with the current time of day in milliseconds as the initial state.
Random(long seed) - Construct a random generator with the given seed as the initial state.


A simple example of Alarm Service, using AlarmManager

Alarm Service in Android

AlarmManager class provides access to the system alarm services. These allow you to schedule your application to be run at some point in the future. When an alarm goes off, the Intent that had been registered for it is broadcast by the system, automatically starting the target application if it is not already running. 

In this exercise, a scheduled alarm of 10 seconds will start a service, MyAlarmService. 

Modify main.xml to have two button to start and cancel the alarm.
<?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"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<Button
android:id="@+id/startalarm"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Start"
/>

<Button
android:id="@+id/cancelalarm"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Cancel"
/>

</LinearLayout>

ProgressBar running in AsyncTask

ProgressBar in Android

It's a exercise of a Horizontal ProgressBar which running in a background AsyncTask.

Modify main.xml to have a button to start the progress, and the ProgressBar.
<?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"
 >
<TextView
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 android:text="@string/hello"
 />
<Button
android:id="@+id/playvideoplayer"
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 android:text="- PLAY Video -"
 />
<Button
android:id="@+id/pausevideoplayer"
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 android:text="- PAUSE Video -"
 />
<SurfaceView
android:id="@+id/surfaceview"
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 />
</LinearLayout>

}