How to start PhoneStateListener programmatically?

2019-08-28 17:28发布

问题:

There's an activity in my application. It contains a button. By clicking the button it should be start PhoneStateListener (and BroadcastReceiver?) to catch incoming and outgoing calls. It seems it should be a service.

Does anyone can explain how to start PhoneStateListener (and BroadcastReceiver?) programmatically?

回答1:

you have to used this code and it is 100% work.

(1) you have to start services

startService(new Intent(this, CallServices.class));

(2) you have to make CallServices class and start your contentobser.

public class CallServices extends Service{
private static final String TAG = "CallService";
Context mContext;

@Override
public IBinder onBind(Intent intent) {
    Log.d(TAG, "onBind");
    return null;
}

@Override
public void onCreate() {
    Log.d(TAG, "onCreate");
    mContext=getApplicationContext();   
}

@Override
public void onStart(Intent intent, int startId) {
    //super.onStart(intent, startId);
    Log.d(TAG, "onStart services is started");
       Uri mediaUri = Uri.parse("content://call_log/calls");
       Handler handler = new Handler(){};
       CustomContentObserver custObser = new CustomContentObserver(handler,mContext);        
       mContext.getContentResolver().registerContentObserver(mediaUri, true, custObser);    
}

}

(3) make CustomContentObserver class to getting you to call log.

public class CustomContentObserver extends ContentObserver {
long lastTimeofCall = 0L;
long lastTimeofUpdate = 0L;
long threshold_time = 10000;

public CustomContentObserver(Handler handler,Context con) {
    super(handler);
    this.mContext=con;
    System.out.println("Content obser");
    callflag=true;
}     
@Override 
public boolean deliverSelfNotifications() { 
    return false; 
}

public void onChange(boolean selfChange) {
 super.onChange(selfChange);

 lastTimeofCall = System.currentTimeMillis();
    if(lastTimeofCall - lastTimeofUpdate > threshold_time){         
        if(callflag){           

             System.out.println("Content obser onChange()");
             Log.d("PhoneService", "custom StringsContentObserver.onChange( " + selfChange + ")");
            //if(!callFlag){                   
             String[] projection = new String[]{CallLog.Calls.NUMBER,
                        CallLog.Calls.TYPE,
                        CallLog.Calls.DURATION,
                        CallLog.Calls.CACHED_NAME,
                        CallLog.Calls._ID};         
          Cursor c;
          c=mContext.getContentResolver().query(CallLog.Calls.CONTENT_URI, projection, null, null, CallLog.Calls._ID + " DESC");
          if(c.getCount()!=0){
                c.moveToFirst();
                 lastCallnumber = c.getString(0);
                 lastCallnumber=FormatNumber(lastCallnumber);                     
                 String type=c.getString(1);
                 String duration=c.getString(2);
                 String name=c.getString(3);
                 String id=c.getString(4);
                 System.out.println("CALLLLing:"+lastCallnumber+"Type:"+type);

                 Database db=new Database(mContext);
                 Cursor cur =db.getFirstRecord(lastCallnumber);
                 System.out.println("CUSTOM GALLARY..."+cur.getCount());
                 final String endCall=lastCallnumber;
                 //checking incoming/outgoing call
                 if(type.equals("1")){
                    //incoming call code

                 }else if(type.equals("2")){
                        //outgoing call code
                 } else{
                    //missed call code
                }
            }

        lastTimeofUpdate = System.currentTimeMillis();
    }
}

}

}

in this way you have to read call log data. i am using content Observer because of in htc device can not read phonestateListner that's way.



回答2:

Try this:

public class myActivity extends Activity{

private TelephonyManager telephonyManager = null;

public void onCreate(Bundle savedInstanceState) {

    // setcontentview and other

    button.setOnClickListener(new OnClickListener(){
           public void onClick(View arg0) {
               btnClick();       
           }
    });

}

private void btnClick(){

telephonyManager = (TelephonyManager)getApplicationContext()
                .getSystemService(Context.TELEPHONY_SERVICE);
        telephonyManager.listen(new PhoneStateListener(){

            @Override
            public void onCallStateChanged(int state, String incomingNumber) {
                switch(state){
                    case TelephonyManager.CALL_STATE_IDLE:
                        /*your code*/
                        break;
                    case TelephonyManager.CALL_STATE_OFFHOOK:
                        /*your code*/
                        break;
                    case TelephonyManager.CALL_STATE_RINGING:
                        /*your code*/
                        break;
                }
                //super.onCallStateChanged(state, incomingNumber);
            }

        }, PhoneStateListener.LISTEN_CALL_STATE);

    } 

}