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

时间:2015-03-06 09:00:25

标签: android android-intent android-service android-broadcast android-alarms

这是我的问题,我在启动或启动应用程序时启动了服务,此服务启动警报,每隔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中将我的服务声明为接收者?

2 个答案:

答案 0 :(得分:1)

我最终设法让它发挥作用。

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>

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

答案 1 :(得分:0)

您需要在清单文件中声明您的服务,如此

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

你也需要注册这样的广播

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