我需要在 killCall 函数中使用 Context 对象,但我不知道如何将 Context 对象传递给 KillCall,你能帮我吗?谢谢!
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;
}
}
最佳答案
您可以通过执行 InternetServerCall.this
将 Context
放入 InternetServerCall
中。这是因为所有 Android
Components
都覆盖了 Context
类,其中有 IntentService
。
您还可以在 IntentService
中使用 getApplicationContext()
来获取上下文。你可以看我另一个类似的回答Pass a Context an IntentService .
但是您不能直接显示来自IntentService
的Toast
,因为它需要UI 线程但IntentService
运行到后台线程。您需要使用 Handler
来显示 Toast,如下例
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();
}
});
}
}
关于android - 在 BroadcastReceiver 中使用 IntentService 时如何传递上下文变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23235734/