HelloCW
HelloCW

Reputation: 2255

How to pass context var when I use IntentService in BroadcastReceiver?

I need to use Context object in the function killCall, but I don't know how to pass the Context object to KillCall, could you help me? Thanks!

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;
    }

}

Upvotes: 2

Views: 1696

Answers (2)

Pankaj Kumar
Pankaj Kumar

Reputation: 82958

You can get Context into InternetServerCall by doing InternetServerCall.this. And this is because all Android Components overrides Context class, on of them is IntentService.

You can also use getApplicationContext() into IntentService to get context. You can read my another similar answer Pass a Context an IntentService.


But you can not display Toast from IntentService directly, because it needs UI thread but IntentService runs into background thread. You need to use Handler to show Toast, like below example

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(); 
                }  
          });   
     } 
}

Upvotes: 3

ianhanniballake
ianhanniballake

Reputation: 199805

An IntentService is subclass of Context so you can pass in this:

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

Upvotes: 1

Related Questions