標籤:
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>
android四大組件之BroadcastReceiver ip撥號功能