Reputation: 233
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.widget.TextView;
public class TelephonyDemo extends Activity {
TextView textOut;
TelephonyManager telephonyManager;
PhoneStateListener listener;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Get the UI
textOut = (TextView) findViewById(R.id.textOut);
// Get the telephony manager
telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
// Create a new PhoneStateListener
listener = new PhoneStateListener() {
@Override
public void onCallStateChanged(int state, String incomingNumber) {
String stateString = "N/A";
switch (state) {
case TelephonyManager.CALL_STATE_IDLE:
stateString = "Idle";
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
stateString = "Off Hook";
break;
case TelephonyManager.CALL_STATE_RINGING:
stateString = "Ringing";
break;
}
textOut.append(String.format("\nonCallStateChanged: %s", stateString));
}
};
// Register the listener with the telephony manager
telephonyManager.listen(listener, PhoneStateListener.LISTEN_CALL_STATE);
}
startService();
}
how to make my application run in background? to read phone state whole time?!?!?!?!
Upvotes: 0
Views: 3623
Reputation: 3407
no need to have "Service" in this current question.
You may use BroadcastReceiver component to be able to receive broadcasted intent PHONE_STATE_CHANGED all the time even if your Activiy (Visible/interactive part of your application) is hidden/removed.
this way your app will react each time PHONE STATE actually changing. no need to have a "Listener" mechanism.
see more on BroadCastReceiver at http://developer.android.com/reference/android/content/BroadcastReceiver.html
Upvotes: 1