我正在制作一个警报应用程序,该应用程序会在确切的给定时间由用户启动。
由于Doze模式已经出现,我听说我需要使用setExactAndAllowWhileIdle()
API 23或更高版本。(我在API 26上定位)。
但问题是每当我设置闹钟时,无论如何,它会在3秒后熄灭(此时只有吐司留言)。我不知道为什么。
任何类型的反馈将不胜感激。
注意:我已在BroadcastReceiver
Manifest.xml
public class MainActivity extends AppCompatActivity {
static final String CP ="checkpi";
MediaPlayer mp;
Calendar c= Calendar.getInstance();
TimePickerDialog.OnTimeSetListener otsl;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView textView = (TextView)findViewById(R.id.tv);
Button testbtn = (Button)findViewById(R.id.test);
testbtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
new TimePickerDialog(MainActivity.this,android.R.style.Theme_Holo_Light_Dialog,otsl,
c.get(Calendar.HOUR_OF_DAY),c.get(Calendar.MINUTE),true).show();
}
});
otsl = new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
textView.setText(hourOfDay+":"+minute);
//c.set(Calendar.HOUR_OF_DAY,hourOfDay);
//c.set(Calendar.MINUTE,minute);
setAlarm(c.getTimeInMillis());
}
};
Button canceltestbtn = (Button)findViewById(R.id.canceltest);
canceltestbtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if(!textView.equals("")){
textView.setText("");
}
cancelAlarm();
}
});
}
public void setAlarm(long timeinmils) {
AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
Intent i = new Intent(MainActivity.this,Alarm.class);
PendingIntent pi = PendingIntent.getBroadcast(this,0,i,PendingIntent.FLAG_UPDATE_CURRENT);
am.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP,timeinmils,pi);
}
public void cancelAlarm() {
AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
Intent i = new Intent(MainActivity.this,Alarm.class);
PendingIntent pi = PendingIntent.getBroadcast(this,0,i,PendingIntent.FLAG_UPDATE_CURRENT);
am.cancel(pi);
pi.cancel();
if(pi==null){
Log.v(CP,"Pendingintent==null");
}
else{
Log.v(CP,"Pendingintent!=null");
}
}
}
// ---------------------------------------------
public class Alarm extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context,"Wake up!!",Toast.LENGTH_SHORT).show();
}
}