如何在服务中注册接收器?

时间:2013-07-18 14:54:04

标签: android android-intent service broadcastreceiver

我必须注册一个不属于同一类的接收器。我的意思是,我有一项服务:

service.java

public class service extends Service {

    NotificationManager mNotificationManager;

    @Override
    public IBinder onBind(Intent intent) {
        // Not used
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        checkPref();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

    }

    private void checkPref() {
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(service.this);
        notificationBuilder.setContentTitle("Title");
        notificationBuilder.setContentText("Context");
        notificationBuilder.setTicker("TickerText");
        notificationBuilder.setWhen(System.currentTimeMillis());
        notificationBuilder.setSmallIcon(R.drawable.ic_stat_icon);

        Intent notificationIntent = new Intent(this, service.class);
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

        notificationBuilder.setContentIntent(contentIntent);

        notificationBuilder.setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE);

        mNotificationManager.notify(1, notificationBuilder.build());
    }
}

MyScheduleReceiver.java

public class MyScheduleReceiver extends BroadcastReceiver {

    // Restart service every 30 min
    private static final long REPEAT_TIME = 30 * 1000 * 4;// 1800000 ;

    @Override
    public void onReceive(Context context, Intent intent) {
        Intent service = new Intent(context, service.class);
        context.startService(service);
    }
}

现在我必须注册一个接收器:

registerReceiver(//thereceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));

在onCreate中。我该怎么做?我认为在//thereceiver中我必须写MyScheduleReceiver但当然如果我在服务中写入onCreate它找不到它。我能怎么做?感谢

1 个答案:

答案 0 :(得分:0)

尝试

registerReceiver(yourReceiver, new IntentFilter("android.intent.action.BATTERY_CHANGED"));

您可能需要添加

<uses-permission android:name="android.permission.BROADCAST_STICKY"/>
您的清单文件中的