我正在尝试设置警报以在特定时间开始工作,但是我的警报从未触发,并且我不知道自己缺少什么。我正在使用android api 22。
谢谢。
public class MainActivity extends ProtectedActivity {
@Override
public void onResume() {
super.onResume();
if (terminalSettings.GetSettlementEnabled())
{
startAlarmManager();
}
}
private void startAlarmManager()
{
Intent i = new Intent(MainActivity.this,
AlarmBroadcastReceiver.class);
PendingIntent pi = PendingIntent.getBroadcast(MainActivity.this, 0,
i, 0);
AlarmManager am =( AlarmManager)getSystemService(ALARM_SERVICE);
am.set(AlarmManager.RTC, System.currentTimeMillis() + 1000, pi); //
Millisec * Second * Minute
}
}
类AlarmBroadcastReceiver
public class AlarmBroadcastReceiver extends BroadcastReceiver {
public AlarmBroadcastReceiver() {
super();
}
@Override
public void onReceive(Context context, Intent intent)
{
Toast.makeText(context, "Alarm !!!!!!!!!!",
Toast.LENGTH_LONG).show(); // For example
}
}
在清单中,我添加了这些行
<receiver android:name=".AlarmBroadcastReceiver"></receiver>
<uses-permission android:name="android.permission.WAKE_LOCK"></uses-permission>
最佳答案
您需要致电registerReceiver
public static final String Broadcast_PLAY_NEW_AUDIO = "Some key so you know which broadcast is which";
//Create Receiver
private BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
//Do stuff
}
};
//Register receiver
IntentFilter filter = new IntentFilter(HomeActivity.Broadcast_PLAY_NEW_AUDIO);
registerReceiver(receiver, filter);
//Send Broadcast
Intent broadcastIntent = new Intent(Broadcast_PLAY_NEW_AUDIO);
sendBroadcast(broadcastIntent);