TQC-305 電話接聽監控
這是TQC的305題,
程式碼為自行撰寫,
僅供參考。
主要練習電話接聽監控
注意:AndroidManifest.xml
<uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>
package COM.TQC.GDD03;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract.PhoneLookup;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.widget.TextView;
import android.widget.Toast;
public class GDD03 extends Activity
{
private TextView myTextView1;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findview();
//運用PhoneStateListener監聽電話狀態
//運用PhoneStateListener監聽電話狀態
//電話狀態的Listener
exPhoneCallListener myPhoneStateListener = new exPhoneCallListener();
//取得TelephonyManager
TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
//將電話狀態的Listener加到取得TelephonyManager
telephonyManager.listen(myPhoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
}
public void findview()
{
myTextView1=(TextView)findViewById(R.id.textView1);
}
public class exPhoneCallListener extends PhoneStateListener
{
public void onCallStateChanged(int state, String incomingNumber)
{
switch (state)
{
//電話狀態是閒置的
case TelephonyManager.CALL_STATE_IDLE:
break;
//電話狀態是接起的
case TelephonyManager.CALL_STATE_OFFHOOK:
Toast.makeText(GDD03.this, "正接起電話…", Toast.LENGTH_LONG).show();
getContactPeople(incomingNumber);
break;
//電話狀態是響起的
case TelephonyManager.CALL_STATE_RINGING:
Toast.makeText(GDD03.this, incomingNumber + "正打電話來…", Toast.LENGTH_LONG).show();
break;
default:
break;
}
super.onCallStateChanged(state, incomingNumber);
}
}
private void getContactPeople(String incomingNumber)
{
myTextView1.setTextColor(Color.BLUE);
ContentResolver contentResolver = getContentResolver();
Cursor cursor = null;
String[] projection = new String[]
{ PhoneLookup._ID, PhoneLookup.DISPLAY_NAME, PhoneLookup.LOOKUP_KEY};
Uri uri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(incomingNumber));
cursor = contentResolver.query(uri, projection, PhoneLookup.NUMBER + "?", new String[] {incomingNumber}, null);
if (cursor.getCount() == 0)
{
myTextView1.setText("unknown Number:" + incomingNumber);
} else if (cursor.getCount() > 0)
{
cursor.moveToFirst();
String name = cursor.getString(1);
myTextView1.setText(name + ":" + incomingNumber);
}
}
}
自我LV~