2011-08-24 71 views
0
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(); 

    } 

如何让我的应用程序在后台运行?整个时间阅读手机状态?!?!?!?!如何让android应用程序在后台运行,服务示例?

回答

1

在当前的问题中不需要“服务”。

即使您的Activiy(应用程序的Visible/interactive部分)被隐藏/删除,您也可以使用BroadcastReceiver组件来始终接收广播的意图PHONE_STATE_CHANGED。
这样,您的应用程序会在每次PHONE STATE实际发生变化时做出反应。不需要有“听众”机制。

查看更多BroadCastReceiver在http://developer.android.com/reference/android/content/BroadcastReceiver.html

相关问题