BroadcastReceiver是广播接收者,系统会在产生事件的时候发送一些广播,比如开机,打电话,等等……
而BroadcastReceiver就可以接收到这些广播从而进行操作。
今天我们要做的就是在拨打号码的时候加上前面的ip号。
首先我们要注册一个BroadcastReceiver,然后我们要在清单文件里配置一些信息首先我们要明确这个BroadcastReceiver 要接收什么样的
广播。
<receiver android:name="com.example.ipcall.MyReceiver" >
<intent-filter>
<action android:name="android.intent.action.NEW_OUTGOING_CALL"/>
</intent-filter>
</receiver>
这个就可以确定接收的是打电话时候发送的广播,然后在权限里还要加上
<uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS"/>
package com.example.ipcall; import android.os.Bundle; import android.app.Activity; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.EditText; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); findViewById(R.id.btn).setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { // TODO Auto-generated method stub EditText edt = (EditText) findViewById(R.id.ip); String ipnumber = edt.getText().toString(); SharedPreferences sp = getSharedPreferences("number",MODE_PRIVATE); Editor editor = sp.edit(); editor.putString("ip",ipnumber).commit(); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } }
package com.example.ipcall; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; public class MyReceiver extends BroadcastReceiver { public MyReceiver() { } @Override public void onReceive(Context context, Intent intent) { // TODO: This method is called when the BroadcastReceiver is receiving // an Intent broadcast. System.out.println("打电话了"); //得到打电话的号码 String number = getResultData(); SharedPreferences sp = context.getSharedPreferences("number",context.MODE_PRIVATE); String ip = sp.getString("ip",""); //设置打电话的好啊 setResultData(ip+number); } }
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity" android:orientation="vertical"> <EditText android:id="@+id/ip" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="请输入"/> <Button android:id="@+id/btn" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/hello_world" /> </LinearLayout>