best way to have a background service making server communication in android application

Currently i am developing a android application that monitors some user behaviours, those behavious are location, accelerometer, pictures, sms and mms information.

I am facing a daunting problem. I am reading information from these services with a service that has a alarm manager.

The alarm manager is has follow:

@Override
    public void onCreate() {
        Log.e(TAG, "onCreate");
        Intent intent = new Intent(this, WorkingService.class);
        PendingIntent pintent = PendingIntent.getService(
                getApplicationContext(), 0, intent, 0);
        AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        calendar.setTimeInMillis(System.currentTimeMillis());
        alarm.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
                15000, pintent);

    }

this will call the onstartcommand of this class every 15 seconds.

@SuppressWarnings("static-access")
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.e(TAG, "onStartCommand");
        super.onStartCommand(intent, flags, startId);

and in the onStartCommand of this service i read stuff from the services that have location updates and other information.

The problem is that this is very costly in terms of power. I was told that the amount of services doesn't have a significant impact on the battery but accessing those services via alarm manager does. What is the alternatives i have in this problem? and can you confirm that the thing that is consuming more battery in my app is in fact the alarm manager service.

And also if it is, what would be a better way to periodically read from the services and send that data into my web services?

Upvotes: 2

Views: 595

Answers (1)

Anthony
Anthony

Reputation: 3074

Why not try using a thread? Something like this would work:

Thread t = new Thread()

{

    @Override

    public void run()

    {

        while (true)

            {

            try
                {
                Thread.sleep(100);

                } catch (InterruptedException ie)
                {
                    fThreadRunning = false;
                    ie.printStackTrace();
                }   
            }
        }
    };
t.start();

It's obvious that the more you read the location the more you will drain your battery, I would recommend you looking into Android DDMS to see what threads are causing the biggest battery drain within your application.

Upvotes: 1

Related Questions