我正在创建应用程序,其中包含假设要收听来电的服务, 在呼叫结束后弹出一个警告对话框,问题是,只要活动正在运行或在后台,服务正常工作并弹出对话框,但当我关闭活动时,对话框不会弹出,如喜欢听众不再听电话。 需要帮助!
这就是我从我的活动中调用服务的方式:
public void onClick(View v) {
switch (v.getId()) {
case R.id.start:
startService(new Intent(getBaseContext(), PhoneService.class));
break;
case R.id.stop:
stopService(new Intent(getBaseContext(), PhoneService.class));
break;
}
}
服务类:
public class PhoneService extends Service {
private static String TAG = "SERVICE";
int currentState;
Context context;
String incomingNumber;
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
// starts the service
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(TAG, "FirstService started");
context = this;
TelephonyManager telephony = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE); // TelephonyManager
// object
CallListener listener = new CallListener();
telephony.listen(listener, PhoneStateListener.LISTEN_CALL_STATE);
// keeps the service going until explicitly stops
return START_STICKY;
}
@Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
Log.i(TAG, "FirstService destroyed");
}
听众类:
public class CallListener extends PhoneStateListener {
@Override
public void onCallStateChanged(int state, String incomingNumber) {
if (TelephonyManager.CALL_STATE_RINGING == state) {
// Incoming call handling
Log.i(TAG, " ring ring ring" + incomingNumber);
currentState = state;
}
if (TelephonyManager.CALL_STATE_OFFHOOK == state) {
// Outgoing call handling and answer
Log.i(TAG, " ofhook" + incomingNumber);
currentState = state;
}
if (TelephonyManager.CALL_STATE_IDLE == state) {
// Device back to normal state (not in a call)
Log.i(TAG, " idle" + incomingNumber);
if (currentState == TelephonyManager.CALL_STATE_OFFHOOK) {
Toast.makeText(context,"phone number dialed is "+ PhoneService.this.incomingNumber,Toast.LENGTH_SHORT).show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage("Who is this person?").setCancelable(false).setPositiveButton("1",new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog, int id) {
}
})
.setNegativeButton("0",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog, int id) {
}
});
AlertDialog alert = builder.create();
alert.getWindow().setType(
WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
alert.show();
}
currentState = state;
}
}
}
答案 0 :(得分:0)
将您的服务更改为从IntentService
派生,并删除onBind
和onStartCommand
的覆盖(让系统处理这些覆盖)。
将您的代码放入onHandleIntent
覆盖。
不同的服务类型的处理方式不同 - 绑定服务仅在活动运行时运行,但可以随时启动意向服务。您可以阅读有关服务类型here的更多信息。