我的應用程序有一個簡單的服務,當用戶撥打或接聽電話時,我需要暫停該服務,服務必須在通話結束後恢復。如何在收到來電時暫停服務,並在通話結束後恢復服務?
這裏是我的主要活動樣子: -
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent(getApplicationContext(), MyService.class);
startService(intent);
TelephonyManager TelephonyMgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
TelephonyMgr.listen(new TeleListener(),
PhoneStateListener.LISTEN_CALL_STATE);
}
class TeleListener extends PhoneStateListener {
public void onCallStateChanged(int state, String incomingNumber) {
super.onCallStateChanged(state, incomingNumber);
switch (state) {
case TelephonyManager.CALL_STATE_IDLE:
Toast.makeText(getApplicationContext(), "CALL_STATE_IDLE",
Toast.LENGTH_LONG).show();
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
Toast.makeText(getApplicationContext(), "CALL_STATE_OFFHOOK",
Toast.LENGTH_LONG).show();
break;
case TelephonyManager.CALL_STATE_RINGING:
Toast.makeText(getApplicationContext(), incomingNumber,
Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(), "CALL_STATE_RINGING",
Toast.LENGTH_LONG).show();
break;
default:
break;
}
}
}}
這裏是我服務類文件: -
public class MyService extends Service {
private static final String TAG = "MyService";
private boolean isRunning = false;
@Override
public void onCreate() {
Log.i(TAG, "Service onCreate");
isRunning = true;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(TAG, "Service onStartCommand");
new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < Integer.MAX_VALUE; i++) {
try {
Thread.sleep(1000);
} catch (Exception e) {
}
if (isRunning) {
Log.i(TAG, "Service running");
}
}
stopSelf();
}
}).start();
return Service.START_STICKY;
}
@Override
public IBinder onBind(Intent arg0) {
Log.i(TAG, "Service onBind");
return null;
}
@Override
public void onDestroy() {
isRunning = false;
Log.i(TAG, "Service onDestroy");
}}
從TeleListener類在MainActivity我能夠獲取電話狀態。我的問題是,當TelephonyManager等於CALL_STATE_OFFHOOK我需要暫停爲MyService當TelephonyManager等於CALL_STATE_IDLE我需要恢復爲MyService
我已經宣佈所有這些。我需要暫停並恢復CALL_STATE_OFFHOOK和CALL_STATE_IDLE – Karthik
上的服務。它的工作正常,但它只在應用程序打開時工作,但我需要像服務一樣隨時工作。 – Karthik