Chintan
Chintan

Reputation: 936

Write Background service in Android

My android app has requirement to schedule a task at certain time. It could be daily, weekly, monthly, etc. So while inserting input data, if user selects "daily". There will be back ground service, which will insert same data daily.

I tried to create Service and corresponding receiver class, however it looks like service doesn't run automatically. Can someone tell me what is missing?

Receiver classes

     public class MyScheduleReceiver extends BroadcastReceiver {

      // Restart service every 30 seconds
      private static final long REPEAT_TIME = 1000 * 30;

      @Override
      public void onReceive(Context context, Intent intent) {
        AlarmManager service = (AlarmManager) context
            .getSystemService(Context.ALARM_SERVICE);
        Intent i = new Intent(context, MyStartServiceReceiver.class);
        PendingIntent pending = PendingIntent.getBroadcast(context, 0, i,
            PendingIntent.FLAG_CANCEL_CURRENT);
        Calendar cal = Calendar.getInstance();
        // Start 30 seconds after boot completed
        cal.add(Calendar.SECOND, 30);
        //
        // Fetch every 30 seconds
        // InexactRepeating allows Android to optimize the energy consumption
        service.setInexactRepeating(AlarmManager.RTC_WAKEUP,
            cal.getTimeInMillis(), REPEAT_TIME, pending);

        // service.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
        // REPEAT_TIME, pending);
        Toast.makeText(context, "Receving", Toast.LENGTH_SHORT).show();

      }



   public class MyStartServiceReceiver extends BroadcastReceiver {

      @Override
      public void onReceive(Context context, Intent intent) {
        Intent service = new Intent(context, LocalWordService.class);
        context.startService(service);
      }
    } 

Android Menifest.xml

   <service
    android:name=".LocalWordService"
    android:label="LocalWordService" >
    </service>

    <receiver android:name="MyScheduleReceiver" >
    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED" />
    </intent-filter>
</receiver>
<receiver android:name="MyStartServiceReceiver" >
</receiver>

Now when i start application, i call one activity class which basically call the service using below code...but nothing is happening after every 30 seconds.

   Intent mServiceIntent = new Intent(this, LocalWordService.class);
        startService(mServiceIntent);

Service class

    public class LocalWordService extends Service {
private final IBinder mBinder = new MyBinder();
private ArrayList<String> list = new ArrayList<String>();

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

}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {

    Toast.makeText(this, "Starting", Toast.LENGTH_SHORT).show();
    Random random = new Random();
    if (random.nextBoolean()) {
        list.add("Linux");
    }
    if (random.nextBoolean()) {
        list.add("Android");
    }
    if (random.nextBoolean()) {
        list.add("iPhone");
    }
    if (random.nextBoolean()) {
        list.add("Windows7");
    }
    if (list.size() >= 20) {
        list.remove(0);
    }
    return Service.START_NOT_STICKY;
    }

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

  public class MyBinder extends Binder {
    LocalWordService getService() {
        return LocalWordService.this;
    }
}

public List<String> getWordList() {
    return list;
}

   }

Please advice, what is missing?

Upvotes: 2

Views: 7544

Answers (3)

Vikrant
Vikrant

Reputation: 1252

Simple way to Create Service.

Create a Class Name as DocService

     import java.io.File;
     import java.util.ArrayList;
     import android.app.Service;
     import android.content.Intent;
     import android.os.Bundle;
     import android.os.Environment;
     import android.os.IBinder;
     import android.os.ResultReceiver;
     import backup.PostFile;

     public class DocService extends Service{

    Intent intent;
    ArrayList<File>fileList;
    String fileType;

    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return null;
    }


    @SuppressWarnings("deprecation")
    @Override
    public void onStart(Intent intent, int startId) {
        // TODO Auto-generated method stub
        super.onStart(intent, startId);

        this.intent = intent;
        fileList = new ArrayList<File>();
        //new PostFile().execute();

        if(intent.hasExtra("doc"))
        {
            fileType = intent.getStringExtra("doc");
            new PostDocFileThread().start();
        }
    }

    class PostDocFileThread extends Thread
    {
        public void run()
        {

            try 
            {
    Thread.sleep(5000);
    //Do your Stuff here.           

            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}

Then In an Activity Calling a Service

public class MainActivity extends Activity {

    static Button docBtn;

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

        docBtn = (Button)findViewById(R.id.backup_documents);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }



    public void onBackupDocumentClick(View v)
    {

            //new BackupDocument().execute();
            docBtn.setEnabled(false);
            Intent i = new Intent("com.example.backuprestore.DocService");
            i.putExtra("doc", "doc");
            i.putExtra("resReceiver", theReceiver);
            startService(i);
            Toast.makeText(getApplicationContext(), "Backup process has been started in background.",Toast.LENGTH_LONG).show();
        }

    }

And Finally declare your service in AndroidManifest XML



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

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

    <service android:name="com.example.backuprestore.DocService" >
        <intent-filter>
            <action android:name="com.example.backuprestore.DocService" />

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

Upvotes: 0

Chintan
Chintan

Reputation: 936

Current Alarm Manager state:




 Realtime wakeup (now=2013-02-27 20:32:52):



 RTC_WAKEUP #1: Alarm{412e05f0 type 0 com.android.providers.calendar}
    type=0 when=+20h57m39s289ms repeatInterval=0 count=0
    operation=PendingIntent{412e05e0: PendingIntentRecord{412e04f0 com.androi
roviders.calendar broadcastIntent}}
  RTC_WAKEUP #0: Alarm{41566480 type 0 android}
    type=0 when=+10h56m12s700ms repeatInterval=3725515 count=0
    operation=PendingIntent{4162dbc0: PendingIntentRecord{41591808 android br
castIntent}}
  RTC #1: Alarm{41532120 type 1 android}
    type=1 when=+22h27m7s419ms repeatInterval=0 count=0
    operation=PendingIntent{4154e7c8: PendingIntentRecord{415adb68 android br
castIntent}}
  RTC #0: Alarm{414eb330 type 1 com.android.calendar}
    type=1 when=+3h27m7s419ms repeatInterval=0 count=0
    operation=PendingIntent{414eb320: PendingIntentRecord{4166c020 com.androi
alendar broadcastIntent}}

  Elapsed realtime wakeup (now=+1h5m9s472ms):
  ELAPSED_WAKEUP #1: Alarm{415608e0 type 2 android}
    type=2 when=+56m18s779ms repeatInterval=0 count=0
    operation=PendingIntent{412fbbc0: PendingIntentRecord{412d26f0 android br
castIntent}}
  ELAPSED_WAKEUP #0: Alarm{41b31c20 type 2 com.android.phone}
    type=2 when=+21s200ms repeatInterval=0 count=0
    operation=PendingIntent{41b31c10: PendingIntentRecord{4163fea8 com.androi
hone broadcastIntent}}
  ELAPSED #3: Alarm{41b21d40 type 3 android}
    type=3 when=+22h57m0s588ms repeatInterval=0 count=0
    operation=PendingIntent{41567800: PendingIntentRecord{41b61370 android br
castIntent}}
  ELAPSED #2: Alarm{41b792e8 type 3 android}
    type=3 when=+9m50s528ms repeatInterval=1800000 count=1
    operation=PendingIntent{415af0b0: PendingIntentRecord{41b791c0 android br
castIntent}}
  ELAPSED #1: Alarm{415d6648 type 3 android}
    type=3 when=+7m30s477ms repeatInterval=0 count=0
    operation=PendingIntent{415652b0: PendingIntentRecord{41bba838 android br
castIntent}}
  ELAPSED #0: Alarm{417b4448 type 3 android}
    type=3 when=+7s294ms repeatInterval=0 count=0
    operation=PendingIntent{4162f708: PendingIntentRecord{415c23a0 android br
castIntent}}

  Broadcast ref count: 0

  Alarm Stats:
  android
    20685ms running, 0 wakeups
    65 alarms: act=android.intent.action.TIME_TICK flg=0x40000014
    2 alarms: act=com.android.server.action.NETWORK_STATS_POLL flg=0x14
    6 alarms: act=com.android.server.ThrottleManager.action.POLL flg=0x14
    1 alarms: act=com.android.server.NetworkTimeUpdateService.action.POLL flg
14
  com.android.providers.calendar
    8935ms running, 1 wakeups
    1 alarms: act=com.android.providers.calendar.intent.CalendarProvider2 flg
14
  com.android.phone
    2632ms running, 63 wakeups
    63 alarms: act=com.android.internal.telephony.gprs-data-stall flg=0x14

Upvotes: 3

julien dumortier
julien dumortier

Reputation: 1303

I made a tutorial that describes how this works (all the code is downloadable and described). maybe it can help you. Attention, in French!

http://julien-dumortier.fr/service-et-binding-sous-android/

Upvotes: 0

Related Questions