2013-07-18 81 views
0

我必须注册一个接收器,它不在同一个类中。我的意思是,我有一个服务:如何在服务中注册Receiver?

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它不能找到它。我能怎么做?由于

+0

什么是你想怎么办?您有注册通知的服务,并且在该通知中您将再次启动该服务?其实你会发送一个意图,但在我看来,你在'MyScheduleReceiver'中做什么是毫无意义的。另外,'service#checkPref'在我看来并没有正确创建Intent,因为它没有指向一个Activity类。 – gunar

+0

简而言之,就是在电池更换后出现通知。现在通知仅在清单中声明的​​BOOT_COMPLETED上启动,但是如果我想在电池更改时显示通知,我该怎么办?我想我必须在java中以编程方式声明意图?我不能只从'BOOT_COMPLETED'改变为'BATTERY_CHANGED' ..不能以这种方式工作。 –

回答

0

尝试

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

你可能会需要添加

<uses-permission android:name="android.permission.BROADCAST_STICKY"/> 

清单档案中的

相关问题