asad_hussain
asad_hussain

Reputation: 2011

Alarm not getting called in android

I am trying to learn the functionality of AlarmManager in android. I am trying to call the alarm after every 10 second.But the problem is that i am getting a blank screen.Then i found that the intent which i am trying to call at the wake of alarm is not getting called.Please someone help me with this?

MainActivity.java

public class MainActivity extends AppCompatActivity {
    private AlarmManager alarmMgr;
    private PendingIntent alarmIntent;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        alarmMgr = (AlarmManager)this.getSystemService(Context.ALARM_SERVICE);
        Intent intent = new Intent(this, AlarmReceiver.class);
        alarmIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
        Log.d("asd","initialized alarmintent");
        alarmMgr.set(AlarmManager.ELAPSED_REALTIME,
                SystemClock.elapsedRealtime()+10*1000, alarmIntent);

                        Log.d("asd", "alarm set");
    }
}

AlarmReceiver.java

public class AlarmReceiver extends AppCompatActivity
{
    TextView tv;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.intent_layout);
        Log.d("asd","writing textview");
        tv=(TextView)findViewById(R.id.textview);
        tv.setText("called");
    }

}

Upvotes: 0

Views: 57

Answers (1)

Lucas Crawford
Lucas Crawford

Reputation: 3118

You are calling PendingIntent wrong:

Intent intent = new Intent(this, AlarmReceiver.class);
alarmIntent = PendingIntent.getBroadcast(this, 0, intent, 0);

See how you are calling PendingIntent.getBroadcast(this, 0, intent, 0)

This is wrong because your AlarmReceiver is an Activity (not a BroadcastReceiver like you are telling the pending intent it is). Try calling it like this:

alarmIntent = PendingIntent.getActivity(this, 0, intent, 0);

It is just the wrong use of pending intent that is your problem :)

Here is documentation:

http://developer.android.com/reference/android/app/PendingIntent.html

EDIT: The documentation also says:

Note that the activity will be started outside of the context of an existing activity, so you must use the Intent.FLAG_ACTIVITY_NEW_TASK launch flag in the Intent.

So make sure you are doing this as well.

Upvotes: 1

Related Questions