服务中的广播接收器未收到警报信号

Broadcast receiver in a service doesn't receive alarm signal

这是我的问题,我有一个服务在启动或应用程序启动时启动,该服务启动一个警报,每 x 分钟下载一个文件。 问题是广播接收器似乎没有收到任何东西。

相关代码如下:

@Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Intent alarmIntent = new Intent(this, ServiceCalendrier.class);
        pendingIntent = PendingIntent.getBroadcast(this, 0, alarmIntent, 0);

        Toast.makeText(this, "My Service Started ", Toast.LENGTH_LONG).show();
        startAlarm();

        return Service.START_NOT_STICKY;
    }



    public void startAlarm() {
        manager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
        int interval =5000;

        manager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), interval, pendingIntent);
        Toast.makeText(this, "Alarm Set", Toast.LENGTH_SHORT).show(); //this toast is printed
    }

    private final BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context arg0, Intent arg1) {
            getIcs(arg0);// download function
            Toast.makeText(arg0, "getICS", Toast.LENGTH_LONG).show();// this one doesn't appear
        }

    };

我是否必须在我的 AndroidManifest 中将我的服务声明为接收方?

您需要像这样在清单文件中声明您的服务

  <application>
</activity>
........
..........
</activity>
        <service android:name=".ServiceNameClass"></service>
    </application>

你还需要像这样注册你的广播

LocalBroadcastManager.getInstance(getBaseContext()).registerReceiver(mMessageReceiver,new IntentFilter("my-event"));

我最终成功了。

public void startAlarm() {
        manager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
        int interval =5000;//7200000;
        IntentFilter myFilter = new IntentFilter("WhatEverYouWant");

        Intent alarmIntent = new Intent("WhatEverYouWant");
        pendingIntent = PendingIntent.getBroadcast(this, 0, alarmIntent, 0);
        registerReceiver(receiver, myFilter);

        manager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), interval, pendingIntent);
        Toast.makeText(this, "Alarm Set", Toast.LENGTH_SHORT).show();
    }

androidManifest:

<service android:enabled="true" android:name="MyService">
            <receiver android:name="MyService">
                <intent-filter>
                    <action android:name="WhatEverYouWant" />
                </intent-filter>
            </receiver>
        </service>
    </application>

我还有一些工作要了解它的工作原理并清理我的代码,但非常感谢您的帮助