1. 外拨电话的广播接收者:
首先我们示例工程一览表如下:
(2)首先我们还是买一个收音机,定义一个OutCallReceiver继承自BroadcastReceiver,onReceive()方法中定义了监听到广播,要执行的操作:
public class OutCallReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) { SharedPreferences sp = context.getSharedPreferences("config", 0); // 修改用户拨打的电话号码, 在号码前面加上17951 String number = getResultData(); System.out.println("------有外拨电话出去了。" + number); if (number.startsWith("0")) { setResultData(sp.getString("ipnumber", "")+ number); } setResultData(null); }}
(3)装电池 和 调频道,在AndroidManifest.xml文件中配置:
<receiver android:name="com.itheima.ipdailer.OutCallReceiver">
<intent-filter > <action android:name="android.intent.action.NEW_OUTGOING_CALL"/> </intent-filter> </receiver>
这里注意添加一个外接电话拨入权限:<uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS"/>
2. 工程代码总览图:
(1)activity_main.xml:
(2)MainActivity.java:
package com.itheima.ipdailer;import android.app.Activity;import android.content.SharedPreferences;import android.content.SharedPreferences.Editor;import android.os.Bundle;import android.view.View;import android.widget.EditText;import android.widget.Toast;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 = this.getSharedPreferences("config", 0); et_ipnumber.setText(sp.getString("ipnumber", "")); } public void save(View view){ String ipnumber = et_ipnumber.getText().toString().trim(); Editor editor = sp.edit(); editor.putString("ipnumber", ipnumber); editor.commit(); Toast.makeText(this, "设置成功", 0).show(); }}
(3)OutCallReceiver.java:
package com.itheima.ipdailer;import android.content.BroadcastReceiver;import android.content.Context;import android.content.Intent;import android.content.SharedPreferences;//买一个收音机public class OutCallReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { SharedPreferences sp = context.getSharedPreferences("config", 0); // 修改用户拨打的电话号码, 在号码前面加上17951 String number = getResultData(); System.out.println("------有外拨电话出去了。" + number); if (number.startsWith("0")) { setResultData(sp.getString("ipnumber", "")+ number); } setResultData(null); }}
(4)AndroidManifest.xml:
//添加一个外接电话拨入的权限 //装电池,调频道