簡體   English   中英

將BroadcastReceiver意圖發送到服務

[英]Sending a BroadcastReceiver intent to a service

通常,您可以啟動此類服務

Intent i = new Intent(context,MessageService.class);
context.startService(i);

但我想要做的是將BroadcastReceiver中收到的意圖發送給服務。 如果我按照上面顯示的方式啟動服務,不會從BroadcastReceiver正確的意圖?

基本上我只是希望我的BroadcastReceiver啟動我的服務,然后讓服務本身處理收到的意圖

這可能嗎?

從BroadcastReceiver發送Intent到服務:

Intent intent = new Intent(context,MessageService.class);
String value = "String you want to pass";
String name = "data";
intent.putExtra(name, value);
context.startService(intent);

onStartCommand服務方法中的Reciver Intent:

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Toast.makeText(this, "service starting", Toast.LENGTH_SHORT).show();
    if (intent.getStringExtra("data") != null) {
     {
       String str=intent.getStringExtra("data");//get data here sended from BroadcastReceiver 
     }

    return super.onStartCommand(intent,flags,startId);
}

關於我們如何在Service和BroadcastReceiver之間進行通信,請參閱此帖子

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM