我需要在函数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;
}
}
答案 0 :(得分:3)
通过执行Context
,您可以InternetServerCall
进入InternetServerCall.this
。这是因为所有Android
Components
覆盖Context
类,其中IntentService
。
您还可以getApplicationContext()
使用IntentService
来获取上下文。您可以阅读我的另一个类似答案Pass a Context an IntentService。
但您无法直接从Toast
显示IntentService
,因为它需要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();
}
});
}
}
答案 1 :(得分:1)
IntentService
是Context
的子类,因此您可以传递this
:
@Override
protected void onHandleIntent(Intent intent) {
HandleCall.killCall(this);
}