天天看點

利用廣播實作ip撥号

<uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS"/>
           
<!-- 定義了一個廣播接收者,new出來了一個收音機,設定action就是相當于設定了監聽的頻道 -->
        <receiver android:name=".OutCallReceiver" >
            <intent-filter>
                <action android:name="android.intent.action.NEW_OUTGOING_CALL" />
            </intent-filter>
        </receiver>
           
<TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="請輸入要設定的ip電話号碼" />

    <EditText
        android:id="@+id/et_ipnumber"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="phone" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="click"
        android:text="确定" />
           

OutCallReceiver

package org.gentry.ipdail;

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

public class OutCallReceiver extends BroadcastReceiver {
	/**
	 * 當有廣播時間産生的時候,就會執行onReceive方法
	 */
	@Override
	public void onReceive(Context context, Intent intent) {
		String number = getResultData(); // 外撥的電話号碼
		// 替換掉這個号碼
		SharedPreferences sp = context.getSharedPreferences("config",
				Context.MODE_PRIVATE);
		String ipnumber = sp.getString("ipnumber", "");
		String newnumber = ipnumber + number;
		// 設定外撥的電話号碼
		setResultData(newnumber);
	}

}
           

MainActivity

package org.gentry.ipdail;

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);
		// 程式下次打開時edittext内容存在
		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(this, "設定完成", Toast.LENGTH_SHORT).show();
	}
}