Android系统重启注册闹钟报错:无法解析getSystemService()方法
Hey there, let's break down your issues step by step:
1. Is "Cannot resolve method getSystemService()" a syntax error?
Nope, this isn't a syntax error—it's a compile-time method resolution error. Here's why:
Starting from Android API 26 (Android 8.0), the Context.getSystemService() method requires you to pass a specific service class (like AlarmManager.class) or the corresponding string constant (like Context.ALARM_SERVICE) to specify which system service you want to retrieve. Your current code calls context.getSystemService() without any arguments, so the compiler can't find a matching method signature, hence the error.
2. Can you use Context in this scenario?
Absolutely! The onReceive() method of BroadcastReceiver is explicitly passed a valid Context instance, which is perfectly safe to use here. This context is designed exactly for cases like accessing system services, creating pending intents, etc.—so you're on the right track using it.
Fixing Your Code
The main issue is missing arguments in your getSystemService() calls. Here's how to correct them:
Option 1 (API 26+ Recommended)
Use the type-safe method signature introduced in API 26:
AlarmManager alarmManager = context.getSystemService(AlarmManager.class); AlarmManager alarmManager2 = context.getSystemService(AlarmManager.class);
Option 2 (Backward Compatible)
If you need to support devices running older Android versions, use the string constant version (requires casting):
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); AlarmManager alarmManager2 = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Additional Notes
- Don't forget to declare the
RECEIVE_BOOT_COMPLETEDpermission in yourAndroidManifest.xml, and register yourRebootBroadcastwith the corresponding intent filter:<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" /> <application ...> <receiver android:name=".RebootBroadcast"> <intent-filter> <action android:name="android.intent.action.BOOT_COMPLETED" /> </intent-filter> </receiver> </application> - Also, take a look at your
PendingIntentcreation: you're using the incomingintent(which is theACTION_BOOT_COMPLETEDintent) for bothpendingIntentandpendingIntent2. This means when the alarm triggers, it'll send the boot completed action again, which will re-run yourRebootBroadcast—probably not what you want. Instead, create anIntentpointing to the specificBroadcastReceiveryou want to handle the alarm trigger.
内容的提问来源于stack exchange,提问作者cvvw

