Tuesday 28 August 2012

Start a Service with Alarm Manager Android

At times we need to start or stop a service once a day, once a week or anything like that. We can use AlarmManager in android to start or stop a service at a particular time automatically. This also helps us to start or stop our service at regular intervals.

Here we are dealing with an example to start a service every hour from the time of installation of the application.

Firstly, we will create a class named myService.class. This will be our service. One thing to be noted is that all service classes extends Service. myService.class will be like this.

public class Service_class extends Service {


    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
        return START_STICKY;
    }

    @Override
    public void onDestroy() {

        super.onDestroy();
        Toast.makeText(this, "Service Stopped", Toast.LENGTH_LONG).show();

    }

    @Override
    public void onCreate() {
        super.onCreate();
    }

}

here in the onStartCommand method, we return START_STICKY this means that, the service will not be stopped until we manually stop the service.

Now in the main activity, we will have two click listeners for the two buttons ( one for starting the service and the other one for stopping the service ) and the AlarmManager which will start the service at the start of every hour.

public class Main extends Activity {

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    // Start service using AlarmManager

    Calendar cal = Calendar.getInstance();
    cal.add(Calendar.SECOND, 10);
    Intent intent = new Intent(Main.this, Service_class.class);
    PendingIntent pintent = PendingIntent.getService(Main.this, 0, intent,
            0);
    AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
            36000 * 1000, pintent);

    // click listener for the button to start service
    Button btnStart = (Button) findViewById(R.id.button1);
    btnStart.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            startService(new Intent(getBaseContext(), Service_class.class));

        }
    });

    // click listener for the button to stop service
    Button btnStop = (Button) findViewById(R.id.button2);
    btnStop.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            stopService(new Intent(getBaseContext(), Service_class.class));
        }
    });
}

main.xml


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

<Button
    android:id="@+id/button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="14dp"
    android:text="@string/startservice" />

<Button
    android:id="@+id/button2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/button1"
    android:layout_below="@+id/button1"
    android:layout_marginTop="38dp"
    android:text="@string/stopservice" />

</RelativeLayout>

While executing the application, the service will start every hour or when the button start service is pressed. The service will stop only when the stop service button is pressed.

one more thing to be done is that you will have to declare the service in the manifest to make it functional.

<service android:name=".Service_class" />


HAPPY CODING  :)

Monday 27 August 2012

Android Ice Cream Sandwich theme (ICS) color codes

Here are some of the color values for ICS theme which might be usefull for you.
screen_background_holo_light #fff3f3f3
screen_background_holo_dark  #ff000000
background_holo_dark         #ff000000
bright_foreground_disabled_holo_dark #ff4c4c4c
bright_foreground_disabled_holo_light  #ffb2b2b2
dim_foreground_holo_dark  #bebebe
dim_foreground_disabled_holo_dark  #80bebebe
dim_foreground_inverse_holo_dark   #323232
dim_foreground_inverse_disabled_holo_dark  #80323232
hint_foreground_holo_dark  #808080
dim_foreground_holo_light #323232
dim_foreground_disabled_holo_light  #80323232
dim_foreground_inverse_holo_light   #bebebe
dim_foreground_inverse_disabled_holo_light #80bebebe
hint_foreground_holo_light   #808080
highlighted_text_holo_dark"  #6633b5e5
highlighted_text_holo_light  #6633b5e5
link_text_holo_dark  #5c5cff
link_text_holo_light #0000ee 

Status bar Notification in Android

In this tutorial, we will deal with making a simple Status Bar Notification in Android. We will implement a sample application having two activities Main and Content. Main is the default activity which is launched when the activity starts. Content is launched when we click on the notification.

First of all declare the two activities in the manifest.

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

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name=".TestActivity" />
</application>
Now we will code the default launcher activity Main

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    // click listener for the button to start Notification
    Button btnNotify = (Button) findViewById(R.id.button1);
    btnNotify.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            createNotification();

        }
    });
}

private void createNotification() {

    NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    int unique_id = 145558;
    Intent nintent = new Intent();
    nintent.setClass(this, TestActivity.class);
    PendingIntent pin = PendingIntent.getActivity(getApplicationContext(),
            0, nintent, 0);
    String title = "Notification";
    String body = "This is a new notification";
    Notification n = new Notification(R.drawable.ic_launcher, body,
            System.currentTimeMillis());
    n.contentIntent = pin;
    n.setLatestEventInfo(getApplicationContext(), title, body, pin);

    n.defaults = Notification.DEFAULT_ALL;
    nm.notify(unique_id, n);

}

The layout main.xml will have a button alone and will be like this.

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

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="14dp"
        android:text="Show Notification" />


</RelativeLayout>
The activity Content which is to loaded when we click on the notification will be like this.

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.test);
    TextView tv = (TextView) findViewById(R.id.textView1);
    tv.setText("Notification is the source of this Activity");
    NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    nm.cancel(145558);
}
the xml layout test.xml will have a TextView and is shown below.

<?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:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="20dip"
        android:text="This activity is launched from the notification" />

</LinearLayout>
And finally we are done. 

Thursday 17 May 2012

Popup menu - android Sample Code

How to implement a popup menu - Android 2.1 


Popup Menu is available in Android SDK 11 on wards. Here I am implementing the concept of popup menu in SDK 7. A Button when clicked should show a Popup Menu. 

In the onCreate of the main activity we have to inflate the layout of the menu which we intend to show as popup.

 inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
 popupView = inflater.inflate(R.layout.menu_layout, null, false);
Here, menu_layout is the desired layout you wish to show as popup.
the onClick method for the button to show the popup is

public void showPopup(View view) {
    pw = new PopupWindow(getApplicationContext());
    pw.setTouchable(true);
    pw.setFocusable(true);
    pw.setOutsideTouchable(true);
    pw.setTouchInterceptor(new OnTouchListener() {
        public boolean onTouch(View v, MotionEvent event) {
            if (event.getAction() == MotionEvent.ACTION_OUTSIDE) {
                pw.dismiss();

                return true;
            }

            return false;
        }
    });

    pw.setWidth(WindowManager.LayoutParams.WRAP_CONTENT);
    pw.setHeight(WindowManager.LayoutParams.WRAP_CONTENT);
    pw.setOutsideTouchable(false);
    pw.setContentView(popupView);
    pw.showAsDropDown(view, 0, 0);

}

Here's the XML layout of the main activity
<?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" >


    <Button
        android:id="@+id/btn1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="50dip"
        android:onClick="showPopup"
        android:text="@string/showPopup" />

</LinearLayout>

DOWNLOAD SAMPLE CODE







Tuesday 15 May 2012

Android Progress Bar with primary and secondary progress - Sample Code

How to implement a horizontal android progress bar with primary and secondary progresses.

Progress bar in android is used to indicate the progress of a task. A horizontal progress bar is the best way to display the progress of a file download , buffering progress or any task of that sort.

This article shows how to implement a horizontal progress bar with a primary progress as well as a secondary progress. As a first step create a sub class for the progress bar.

public class MyProgressBar extends ProgressBar {
    private Paint textPaint;

    public MyProgressBar(Context context) {
        super(context);
        textPaint = new Paint();
        textPaint.setColor(Color.BLACK);
    }

    public MyProgressBar(Context context, AttributeSet attrs) {
        super(context, attrs);
        textPaint = new Paint();
        textPaint.setColor(Color.BLACK);
        setMax(30);
        setProgress(12);
        setSecondaryProgress(20);

    }
}


Here the primary and secondary progresses can set to using the setProgress and setSecondaryProgress methods. It can be set to any variables, the value of which will be shown instantaneously in the progress bar as primary and secondary progresses in the progress bar.

The XML entry of the progress bar in the layout file should refer to this sub class of the progress bar.

A sample XML entry is shown below.
<com.example.doubleProgressBar.MyProgressBar
    android:id="@+id/progressBar1"
    style="?android:attr/progressBarStyleHorizontal"
    android:layout_width="fill_parent"
    android:layout_height="15sp"
    android:layout_marginLeft="1sp"
    android:layout_marginRight="1sp"
    android:layout_marginTop="10sp"
    android:progressDrawable="@drawable/progress" />

A drawable for the progress bar should be created inside the resources for the project.

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:id="@android:id/background">
    <shape>
        <corners android:radius="5dip" />

        <gradient
            android:angle="270"
            android:centerColor="#ff5a5d5a"
            android:centerY="0.75"
            android:endColor="#ff747674"
            android:startColor="#ff5a5d5a" />
    </shape>
</item>
<item android:id="@android:id/secondaryProgress">
    <clip>
        <shape>
            <corners android:radius="5dip" />


            <gradient
                android:angle="270"
                android:centerColor="#32cd32"
                android:centerY="0.75"
                android:endColor="#32cd32"
                android:startColor="#32cd32" />
        </shape>
    </clip>
</item>
<item android:id="@android:id/progress">
    <clip>
        <shape>
            <corners android:radius="5dip" />

            <gradient
                android:angle="270"
                android:endColor="#33B5E5"
                android:startColor="#33B5E5" />
        </shape>
    </clip>
</item>


The colors for the primary and secondary progresses inside this drawable for the progress bar.

DOWNLOAD SAMPLE CODE