如何解决应用程序未在后台运行Android Studio Java
我正在开发一个Android应用,我想激活一个每日警报(我以5分钟为间隔进行测试)。
我使用了brodacast接收器(清单文件中声明的静态接收器), 但该应用仍然无法正常运行。这是我的代码:
清单文件:
</activity> <receiver android:name=".ExecutableService" android:enabled="true" ></receiver </application>
AlarmHandler类:
public class AlarmHandler {
private Context context;
public AlarmHandler(Context context) {
this.context = context;
}
//This will active the alarm
public void setAlarmManager(){
Intent intent = new Intent(context,ExecutableService.class);
PendingIntent sender = PendingIntent.getbroadcast(context,2,intent,0);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
if (alarmManager != null) {
long triggerAfter=60*5*1000;//this will trigger the service after 5 min
long triggerEvery=60*5*1000;//this will repeat alarm every 5 min after that
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,triggerAfter,triggerEvery,sender);
}
}
//This will cancel the alarm
public void cancelAlarm (){
Intent intent = new Intent(context,ExecutableService.class);
PendingIntent sender = PendingIntent.getbroadcast(context,0);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
if (alarmManager != null) {
alarmManager.cancel(sender);
}
}
}
这是广播接收器:
import ...
public class ExecutableService extends broadcastReceiver {
private static final String TAG="Executable Service";
@Override
public void onReceive(Context context,Intent intent) {
//this will be executed at selected interval Notification show
Toast.makeText(context,"Hello World 2! ",Toast.LENGTH_SHORT).show();
Log.d(TAG,"onReceive: it worked ");
Vibrator v=(Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
v.vibrate(VibrationEffect.createOneshot(500,VibrationEffect.DEFAULT_AMPLITUDE));
} else {
//deprecated in API 26
v.vibrate(500);
}}}
这是我激活警报的MainActivty:
public class MainActivity2 extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
AlarmHandler alarmHandler = new AlarmHandler(this);
//cancel the prevIoUs scheduled alarm
alarmHandler.cancelAlarm();
//set the new alarm after one hour
alarmHandler.setAlarmManager();
Toast.makeText(this,"Alarm Set ! ",Toast.LENGTH_SHORT).show();
}
如果这不是我应该在后台运行应用程序并推送通知(或在特定时间进行简单的祝酒)的方式,那么最好的方法是什么?
我还尝试了JobScheduler服务。
解决方法
您将警报开始时间设置为long triggerAfter=60*5*1000;
我建议将其更改为
long triggerAfter =60*5*1000+ System.currentTimeMillis()
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。