Android AlarmManager当前不会执行

时间:2016-02-26 21:59:49

标签: android alarmmanager

在我的android清单中,我已经定义了一个这样的broadcastReceiver:

package com.myexample.mycompany.countdownapp;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.Toast;

import java.util.Calendar;

public class MainActivity extends AppCompatActivity {


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

        //10 seconds later
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.SECOND, 0);


        AlarmManager alarmMgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

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

        alarmMgr.set(AlarmManager.ELAPSED_REALTIME,
                cal.getTimeInMillis(), alarmIntent);

    }




    public static class WarningReceiver extends BroadcastReceiver {

        public Void sendWarningEvent() throws Exception {
            // fire off warning event
            Log.v("WarningReceiver", "sendWarningEvent called from WarningReceiver");
            return null;
        }

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

                Toast.makeText(context,
                        "WarningReceiver.onReceive()",
                        Toast.LENGTH_LONG).show();

                sendWarningEvent();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

然后在我的mainActivity中我有一个WarningReceiver类。整个mainActivity非常小,看起来像这样:

{{1}}

当我运行应用程序时,没有任何东西被解雇。我做错了什么?

1 个答案:

答案 0 :(得分:3)

试试这个:

alarmMgr.set(AlarmManager.RTC_WAKEUP,cal.getTimeInMillis(), alarmIntent);

而不是:

alarmMgr.set(AlarmManager.ELAPSED_REALTIME,cal.getTimeInMillis(), alarmIntent);