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();
}
如何让我的应用程序在后台运行?整个时间阅读手机状态?!?!?!?!
答案 0 :(得分:1)
在当前的问题中无需“服务”。
即使您的Activiy(应用程序的可见/交互式部分)被隐藏/删除,您也可以使用BroadcastReceiver组件始终接收广播的意图PHONE_STATE_CHANGED。
这样你的应用程序每次PHONE STATE实际更改时都会做出反应。不需要“监听”机制。
在http://developer.android.com/reference/android/content/BroadcastReceiver.html
上查看有关BroadCastReceiver的更多信息