2014-04-23 64 views
1

我需要在函數killCall中使用Context對象,但我不知道如何將上下文對象傳遞給KillCall,你能幫我嗎?謝謝!如何在BroadcastReceiver中使用IntentService時傳遞上下文var?

public class ReceiverCall extends BroadcastReceiver { 
    @Override 
    public void onReceive(Context context, Intent intent) { 
     // TODO Auto-generated method stub 

       Intent msgIntent = new Intent(context, InternetServerCall.class);  
       context.startService(msgIntent); 
    } 

} 


public class InternetServerCall extends IntentService{ 

    public InternetServerCall(String name) { 
     super("InternetServerCall"); 
     // TODO Auto-generated constructor stub 
    } 

    @Override 
    protected void onHandleIntent(Intent intent) {  
     HandleCall.killCall(context); //Need context 
    } 

} 


public class HandleCall { 

    public static boolean killCall(Context context) { 
     try { 
      .... 
      Toast.makeText(context, "PhoneStateReceiver kill incoming call Ok",Toast.LENGTH_SHORT).show(); 

     } catch (Exception ex) { // Many things can go wrong with reflection calls 
      return false; 
     } 
     return true; 
    } 

} 

回答

3

您可以通過執行InternetServerCall.this得到ContextInternetServerCall。這是因爲所有AndroidComponents覆蓋Context類,他們是IntentService

您還可以使用getApplicationContext()轉換爲IntentService以獲取上下文。你可以閱讀我的另一個類似的答案Pass a Context an IntentService


但你無法顯示IntentServiceToast直接,因爲它需要UI線程,但IntentService跑入後臺線程。您需要使用Handler顯示吐司,像下面的例子

public class TestService extends IntentService { 


    private Handler handler; 

    public TestService(String name) { 
     super(name); 
     // TODO Auto-generated constructor stub 
    } 

    public TestService() { 
      super("TestService"); 
    } 


    @Override 
    public int onStartCommand(Intent intent, int flags, int startId) { 
     handler = new Handler(); 
     return super.onStartCommand(intent, flags, startId); 
    } 

    @Override 
    protected void onHandleIntent(Intent intent) { 
      // TODO Auto-generated method stub 
     handler.post(new Runnable() { 
       @Override 
       public void run() {   
          Toast.makeText(getApplicationContext(), "Handling Intent..", Toast.LENGTH_LONG).show(); 
       } 
      }); 
    } 
} 
1

IntentServiceContext子類,所以你可以在this傳:

@Override 
protected void onHandleIntent(Intent intent) {  
    HandleCall.killCall(this); 
} 
相關問題