应用程序未在后台运行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()