简体   繁体   中英

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");
    }

}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM