2013-07-18 85 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"/> 

清單檔案中的

相關問題