BroadcastReceiver 之外挂电话的实现

  本案例实现的是:现在一个文本框中输入区号,设置一个广播,每一次打电话时自动的添加电话的前缀(区号) 

xml文件:

    <TextView

            android:layout_width="fill_parent"

            android:layout_height="wrap_content"

            android:text="请输入要设置的ip电话号码" />

 

        <EditText

            android:id="@+id/et_ipnumber"

            android:layout_width="fill_parent"

            android:layout_height="wrap_content"

            android:inputType="phone" />

 

        <Button

            android:onClick="click"

            android:layout_width="fill_parent"

            android:layout_height="wrap_content"

            android:text="确定" />

 

 

MainActivity文件:

 

    public class MainActivity extends Activity {

       

        private EditText et_ipnumber;

        private SharedPreferences sp;

 

        @Override

        protected void onCreate(Bundle savedInstanceState) {

            super.onCreate(savedInstanceState);

            setContentView(R.layout.activity_main);

           

            et_ipnumber = (EditText) findViewById(R.id.et_ipnumber);

            sp = getSharedPreferences("config", MODE_PRIVATE);

            et_ipnumber.setText(sp.getString("ipnumber", ""));//第二个参数表示默认值

           

        }

       

        public void click(View view){

            String ipnumber = et_ipnumber.getText().toString().trim();

            Editor editor = sp.edit();

            editor.putString("ipnumber", ipnumber);

            editor.commit();

            Toast.makeText(MainActivity.this, "设置完毕", 0).show();

           

        }

 

    }

 

 

定义一个继承自BroadcastReceiver的类,用于接收广播:

    public class OutCallReceiver extends BroadcastReceiver {

 

        //当有广播事件产生的时候就会执行onReceive方法

        @Override

        public void onReceive(Context arg0, Intent arg1) {

            System.out.println("onReceive发现了新的外拨电话。。。");

            Log.e("onReceive:", "onReceive发现了新的外拨电话。。。");

            

            String number = getResultData();//外拨的电话号码

            System.out.println("number:"+ number);

            //替换掉这个号码

            SharedPreferences sp = arg0.getSharedPreferences("config", Context.MODE_PRIVATE);

            String ipnumber = sp.getString("ipnumber", "");

            String newnumber = ipnumber + number;

            //设置外拨的电话号码

            setResultData(newnumber);

           

        }

 

    }

 

接下来要在清单文件中设置广播:

在application中:

        <!-- 定义一个广播接收者 new出来了一个收音机,设置action就相当于设置了监听频道 -->

        <receiver android:name=".OutCallReceiver">

            <intent-filter>

                <action android:name="android.intent.action.NEW_OUTGOING_CALL"/>

            </intent-filter>

        </receiver>

 

外挂电话必须要添加相应的权限:

<uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS"/>

 

posted @ 2015-10-25 17:38  飞牛冲天  阅读(207)  评论(0编辑  收藏  举报