Thursday, 6 June 2013

Android Alarm Manager to Start Service every hour

 Start Service every hour


     Hi Guys  Today we will create a service which will start after every hour ,
So we can use such service to fetch  or updated data from web to our app.

Here is simple example.


Service Started

Service Running Background



Steps to Create:
1.) Open Eclipse. Use the New Project Wizard and select Android Project Give the respective project name and other things.

Create simple Layout 
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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <Button
        android:id="@+id/stopBtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="155dp"
        android:text="Stop" />

    <Button
        android:id="@+id/startBtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/stopBtn"
        android:layout_alignLeft="@+id/stopBtn"
        android:layout_marginBottom="41dp"
        android:text="start" />

</RelativeLayout>


In MainActivity.java  copy Paste  following  code 


public class MainActivity extends Activity {

       @Override
       protected void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.activity_main);

              // Start service using AlarmManager

              Calendar cal = Calendar.getInstance();
              cal.add(Calendar.SECOND, 10);
             
              Intent intent = new Intent(this, TestService.class);
      
              PendingIntent pintent = PendingIntent.getService(this, 0, intent, 0);
             
              AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
              //for 30 mint 60*60*1000
              alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
                           60*60*1000, pintent);

              Button startBtn = (Button) findViewById(R.id.startBtn);
              startBtn.setOnClickListener(new OnClickListener() {

                     @Override
                     public void onClick(View v) {
                           // TODO Auto-generated method stub
                           startService(new Intent(getBaseContext(), TestService.class));
                     }
              });

              Button stopBtn = (Button) findViewById(R.id.stopBtn);
              stopBtn.setOnClickListener(new OnClickListener() {

                     @Override
                     public void onClick(View v) {
                           // TODO Auto-generated method stub
                           stopService(new Intent(getBaseContext(), TestService.class));
                     }
              });

       }


}


and here is your Service code 

TestService.java




public class TestService extends Service {

       @Override
       public IBinder onBind(Intent intent) {
              // TODO: Return the communication channel to the service.
              throw new UnsupportedOperationException("Not yet implemented");
       }

       @Override
       public void onCreate() {
              // TODO Auto-generated method stub

              Toast.makeText(getApplicationContext(), "Service Created", 1).show();
              super.onCreate();
       }

       @Override
       public void onDestroy() {
              // TODO Auto-generated method stub
              Toast.makeText(getApplicationContext(), "Service Destroy", 1).show();
              super.onDestroy();
       }

       @Override
       public int onStartCommand(Intent intent, int flags, int startId) {
              // TODO Auto-generated method stub
              Toast.makeText(getApplicationContext(), "Service Running ", 1).show();
              return super.onStartCommand(intent, flags, startId);
       }


}


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


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

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

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.alarmservice.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

        <service            android:name="com.example.alarmservice.TestService"            android:enabled="true"            android:exported="true" >        </service>

    </application>

</manifest>

you can download complete example here, 


Happy Codding :)