在android中设置警报

时间:2015-02-17 01:16:06

标签: android alarmmanager

我正在尝试使用android中的AlarmManager。我有以下代码,应该从单击按钮时设置警报3秒。我没有收到任何错误,但我的AlarmReceiver中的代码从未被触发过。

这是我的活动:

public class MainActivity extends ActionBarActivity {
    private Context context;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        this.context = this;
        Button setAlarm = (Button) findViewById(R.id.button1);
        setAlarm.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Log.i("MAIN", "SETTING ALARM");
                AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
                Intent intent = new Intent(context, AlarmReceiver.class);
                PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
                am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 3000, pi);
                Log.i("MAIN", "ALARM SET");
            }
        });
    }
}

这是我的接收者:

public class AlarmReceiver extends BroadcastReceiver{

    @Override
    public void onReceive(Context context, Intent intent) {
        Log.i("ALARM RECEIVER", "ALARM RECEIVED");
        Toast.makeText(context, "Alarm worked.", Toast.LENGTH_LONG).show();
    }

}

这是我的表现:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.test.alarm"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-permission android:name="android.permission.WAKE_LOCK"></uses-permission>
    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="21" />

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

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

         <receiver android:name=".AlarmReciever"/> 
    </application>

</manifest>

我在logcat中看到闹钟设置输出,所以我知道它已经超过我实际设置闹钟的点,但我的闹钟接收器永远不会被调用。任何帮助将不胜感激。

0 个答案:

没有答案