0

I followed this tutorial for Repeating Alarm Example in Android using AlarmManager: http://javatechig.com/android/repeat-alarm-example-in-android. I want to start an alarm which will trigger an intent service every 10 seconds. But it doesn't work, if there is someone who can help me.

MainActivity code:

package subhi.com.broadcast2;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Toast;

import java.util.Calendar;

public class MainActivity extends AppCompatActivity {

    private PendingIntent pendingIntent;

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


        /* Retrieve a PendingIntent that will perform a broadcast */
        Intent alarmIntent = new Intent(MainActivity.this, MyService.class);
        pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, alarmIntent, 0);

        findViewById(R.id.startAlarm).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                start();
            }
        });

        findViewById(R.id.stopAlarm).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                cancel();
            }
        });

        findViewById(R.id.stopAlarmAt10).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startAt10();
            }
        });
    }


    public void start() {
        AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        int interval = 10000;

        manager.setInexactRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), interval, pendingIntent);
        Toast.makeText(this, "Alarm Set", Toast.LENGTH_SHORT).show();
    }

    public void cancel() {
        AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        manager.cancel(pendingIntent);
        Toast.makeText(this, "Alarm Canceled", Toast.LENGTH_SHORT).show();
    }

    public void startAt10() {
        AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        int interval = 1000 * 60 * 20;

        /* Set the alarm to start at 10:30 AM */
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(System.currentTimeMillis());
        calendar.set(Calendar.HOUR_OF_DAY, 10);
        calendar.set(Calendar.MINUTE, 30);

        /* Repeating on every 20 minutes interval */
        manager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
                1000 * 60 * 20, pendingIntent);
    }
}

The AlarmReciver code, which will start the IntentService:

package subhi.com.broadcast2;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

/**
 * Created by subhi on 2/20/2016.
 */
public class AlarmReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {

        // For our recurring task, we'll just display a message
       //Toast.makeText(context, "I'm running", Toast.LENGTH_SHORT).show();
        Intent intent2=new Intent(context,MyService.class);

        context.startService(intent);
    }
}

The MyService code:

package subhi.com.broadcast2;

import android.app.IntentService;
import android.content.Intent;
import android.widget.Toast;

/**
 * Created by subhi on 2/20/2016.
 */
public class MyService extends IntentService {
    /**
     * Creates an IntentService.  Invoked by your subclass's constructor.
     *
     * @param name Used to name the worker thread, important only for debugging.
     */
    public MyService() {
        super("My_Worker_Thread");
    }

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

    @Override
    public void onDestroy() {
        super.onDestroy();
        Toast.makeText(this,"Service Stopped....",Toast.LENGTH_LONG).show();
    }

    @Override
    protected void onHandleIntent(Intent intent) {

        Toast.makeText(getApplicationContext(),"Good",Toast.LENGTH_LONG).show();

        synchronized (this){


            int count=0;
            while (count<10) {
                try {
                    wait(3000);
                    count++;
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        }


    }
}

Finally the manifest code:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="subhi.com.broadcast2">

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

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

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


        <service android:name=".MyService">
        </service>
    </application>

</manifest>
ucMedia
  • 4,105
  • 4
  • 38
  • 46
Subhi
  • 322
  • 3
  • 11
  • 1
    Why exactly are you using a IntentService when the AlarmSERVICE will deliver an intent to the Broadcast Receiver and you can perform all your required logic there? ... Anyway first immediate problem I see is in your BroadcastReceiver you pass : `context.startService(intent);` (method argument - the delivered intent) not `context.startService(intent2);` (intent2 - your intention to do something else) – Mark Feb 20 '16 at 17:47
  • Also looking at the example you didn't add the permission: `` to your manifest, until you do so your intent filter will not work. – Mark Feb 20 '16 at 17:58
  • Use either a BroadcastReceiver or an IntentService, but not both. For using an IntentService with a PendingIntent, basically use `getService()` instead of `getBroadcast()`, there is some example code here: http://stackoverflow.com/questions/30141631/send-location-updates-to-intentservice/30273481#30273481 – Daniel Nugent Feb 20 '16 at 18:27

1 Answers1

0

The broadcast receiver is having a BOOT_COMPLETED intent filter. Thus the receiver will only receive a broadcast on boot complete. Instead use your MyService intent service in the pending intent as follows

PendingIntent intent = PendingIntent.getService(context, 0, alarmIntent,PendingIntent.FLAG_UPDATE_CURRENT);
Umang
  • 966
  • 2
  • 7
  • 17