retrieve the call number in my android APP
I would like to get the number call when i receive a call in my app.I would like to retrieve it and store it somewhere.
public void onCallStateChanged(int state, String incomingNumber) {
super.onCallStateChanged开发者_Python百科(state, incomingNumber);
.........
incomingNumber contains nothing.
Do you have the permissions?
Note that access to some telephony information is permission-protected. Your application won't receive updates for protected information unless it has the appropriate permissions declared in its manifest file. Where permissions apply, they are noted in the appropriate LISTEN_ flags.
http://developer.android.com/reference/android/telephony/PhoneStateListener.html
Include following permissions in your application manifest as a child of application
.
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
Also include a receiver in manifest
<!-- SAMPLE APPLICATION IS NAME OF OUR APPLICATION -->
<receiver android:name="SampleApplication"
android:enabled="true"
android:exported="true"
android:permission="">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
<action android:name="android.intent.action.PHONE_STATE" />
</intent-filter>
</receiver>
Create a class that extends android.telephony.PhoneStateListener
and implement its onCallStateChanged
public class
class MyPhoneStateListener extends PhoneStateListener
{
public void onCallStateChanged(int state, String incomingNumber)
{
Log.d("SampleApp","Incoming call from: "+incomingNumber);
}
}
Now in you onCreate() call TelephonyManager and add this class as listener:
TelephonyManager myTelManager = (TelephonyManager)getSystemService(TELEPHONY_SERVICE);
MyPhoneStateListener myListner = new MyPhoneStateListener();
myTelManager.listen(myListner, PhoneStateListener.LISTEN_CALL_STATE);
You can check result in LogCat.
EDIT :Complete class which stores response in variable:
import android.app.Activity;
import android.os.Bundle;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
public class SampleApp extends Activity{
private String incomingCallNumber="";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.rating);
TelephonyManager myTelManager =
(TelephonyManager)getSystemService(TELEPHONY_SERVICE);
MyPhoneStateListener myListner = new MyPhoneStateListener();
myTelManager.listen(myListner, PhoneStateListener.LISTEN_CALL_STATE);
}
class MyPhoneStateListener extends PhoneStateListener
{
public void onCallStateChanged(int state, String incomingNumber)
{
SampleApp.this.incomingCallNumber=incomingNumber;
}
}
}
精彩评论