2011-03-14 12 views
17

के साथ सेवा शुरू करें सक्रियण से मेरी सेवा शुरू करने के लिए मैं startService(MyService.class) का उपयोग करता हूं। यह बहुत अच्छा काम करता है, लेकिन एक विशेष मामले में सेवा को अलग-अलग शुरू किया जाना चाहिए। मैं सेवा शुरू करने के लिए कुछ पैरामीटर पास करना चाहता हूं।एंड्रॉइड: पैरामीटर

मैं अपने गतिविधि में निम्नलिखित की कोशिश की:

Intent startMyService= new Intent(); 
startMyService.setClass(this,LocalService.class); 
startMyService.setAction("controller"); 
startMyService.putExtra(Constants.START_SERVICE_CASE2, true); 

startService(startMyService); 

मेरी सेवा में मैं का उपयोग करें:

public class MyIntentReceiver extends BroadcastReceiver { 

@Override 
public void onReceive(Context context, Intent intent) { 

     if (intent.getAction().equals("controller")) 
     { 
       // Intent was received        
     } 

    } 
} 

IntentReceiver OnCreate() में पंजीकृत है इस तरह:

IntentFilter mControllerIntent = new IntentFilter("controller"); 
MyIntentReceiver mIntentReceiver= new MyIntentReceiver(); 
registerReceiver(mIntentReceiver, mControllerIntent); 

इस समाधान के साथ सेवा शुरू होती है लेकिन इरादा प्राप्त नहीं होता है। मैं सेवा कैसे शुरू कर सकता हूं और अपने पैरामीटर कैसे पास कर सकता हूं?

आपकी मदद के लिए धन्यवाद!

+0

MyIntentReceiver क्या है? क्या आप कुछ विशिष्ट प्रसारण सुनना चाहते हैं और अपने सेवा व्यवहार को बदलना चाहते हैं? – Audrius

+0

@ ऑडियस: हाँ, आप सही हैं। MyIntentReceiver का उपयोग मेरी सेवा के व्यवहार को बदलने के लिए किया जाता है। मेरी सेवा में 2 राज्य हैं: एक सेवा शुरू करते समय, एक और जब सेवा चल रही है। – Mike

उत्तर

14

चरण # 1: अपना BroadcastReceiver कार्यान्वयन हटाएं।

चरण # 2: Intent की जांच करें आपकी सेवा onStartCommand() में हो और getAction() के माध्यम से कार्रवाई को देखें।

+2

लेकिन यह केवल क्रिएट के बाद सेवा को बदलने की अनुमति देगा। मैं ऑनक्रेट में वैरिएबल पास करना चाहता हूं, फिर इसे कैसे करें –

24
Intent serviceIntent = new Intent(this,ListenLocationService.class); 
serviceIntent.putExtra("From", "Main"); 
startService(serviceIntent); 
//and get the parameter in onStart method of your service class 

@Override 
public void onStart(Intent intent, int startId) { 
    super.onStart(intent, startId); 
    Bundle extras = intent.getExtras(); 

    if(extras == null) { 
     Log.d("Service","null"); 
    } else { 
     Log.d("Service","not null"); 
     String from = (String) extras.get("From"); 
     if(from.equalsIgnoreCase("Main")) 
      StartListenLocation(); 
    } 
} 
+3

आप सर्विस क्लास –

+1

के साथ-साथ 'ऑनहैंडलइन्टेंट (इरादा इरादा)' – grim

+0

में ऑनस्टार्ट कॉमांड विधि में इरादा ऑब्जेक्ट भी प्राप्त कर सकते हैं, अब यह "ऑनस्टार्ट कमांड" में है – Ton

संबंधित मुद्दे