Android初级教程IP拨号器初识广播接受者

需求:输入ip号码并且保存在本地,监听打电话广播,如果电话号码以0开头,则加上ip区号拨打。

首先定义一个页面布局:

<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:orientation="vertical"
    tools:context=".MainActivity" >

    <EditText
        android:id="@+id/et_ipnumber"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="请输入ip前缀号码" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="click"
        android:text="保存" />

</LinearLayout>

保存用户输入的号码:

package com.example.ipdial;

import android.os.Bundle;
import android.app.Activity;
import android.content.SharedPreferences;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {

	private EditText et_number;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		et_number = (EditText) findViewById(R.id.et_ipnumber);
	}

	public void click(View v) {

		String ipnumber = et_number.getText().toString().trim();
		// 完成保存
		SharedPreferences sp = getSharedPreferences("config", MODE_PRIVATE);

		sp.edit().putString("ipNumber", ipnumber).commit();

		Toast.makeText(this, "保存成功", 1).show();
	}
}

定义广播接受者接收系统打电话广播。并且如果号码0开头,前加ip号码

package com.example.ipdial;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;

public class OutGoingCallReceiver extends BroadcastReceiver {

	@Override
	public void onReceive(Context context, Intent intent) {

		SharedPreferences sp = context.getSharedPreferences("config", 0);
		String ipNumber = sp.getString("ipNumber", "");

		String resultData = getResultData();

		if (resultData.startsWith("0")) {
			setResultData(ipNumber + resultData);
		}

	}

}
广播接受者清单文件配置:

<receiver android:name="com.example.ipdial.OutGoingCallReceiver">
            <intent-filter >
                <action android:name="android.intent.action.NEW_OUTGOING_CALL"/>
            </intent-filter>
        </receiver>

修改打电话的号码需要权限:

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

成功。


你可能感兴趣的:(android,ip拨号)