android-'无法解析方法getSystemService'-在系统重新启动时注册警报

我正在系统重新启动时注册警报,因为在系统重新启动后警报将被终止,但是我收到“无法解析方法getSystemService()”的错误,这是语法错误...

可以在这种情况下使用Context,因为应该在手机重启后调用此功能...

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;



public class RebootBroadcast extends BroadcastReceiver {

    private static final String LOG_TAG = "MyBroadcast ";

    public  RebootBroadcast () {
    }

    @Override
    public void onReceive(Context context, Intent intent) {

        if (intent != null) {
            String action = intent.getAction();

            switch (action) {
                case Intent.ACTION_BOOT_COMPLETED:



                    PendingIntent pendingIntent = PendingIntent.getBroadcast(context,0,intent,0);
                    PendingIntent pendingIntent2 = PendingIntent.getBroadcast(context,1,intent,0);
                    AlarmManager alarmManager = (AlarmManager) context.getSystemService();
                    AlarmManager alarmManager2 = (AlarmManager) context.getSystemService();

                    long timeAtButtonClick = System.currentTimeMillis();
                    long tenSecondsInMillis = 1000 * 10;
                    long nextInMillis = 1000 * 20;


                    String myDate = "2020/05/09 18:00:00";
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
                    Date date = null;
                    try {
                        date = sdf.parse(myDate);
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    long millis = date.getTime();

                    //long diff = millis - timeAtButtonClick;


                    alarmManager.set(AlarmManager.RTC_WAKEUP,   millis, pendingIntent);

                    break;
                default:
                    break;
            }
        }
    }
}
评论
xipsam
xipsam

您应该更改为

(AlarmManager) context.getSystemService()
(AlarmManager) context.getSystemService(Context.ALARM_SERVICE)
点赞
评论
matque
matque

You need to call getSystemService on a Context, hence, why it doesn't work in your ALARM_SERVICE. You can store the context you already pass in as a field and call getSystemService on that.

点赞
评论