有一次忘記是什么情況和女朋友鬧了矛盾,女朋友就是不接我電話,當時我也有點不高興不接我就一直打,打了半天還是不接。我就想啊,寫個Android程序裝在手機上自動打!
思路
當時說寫馬上就寫出來了,因為這個的思路特別簡單,就是寫一個打電話的代碼,然后讓這段代碼循環(huán)調用就好了。
實現(xiàn)
** 寫好撥打電話的權限 **
<uses-permission android:name="android.permission.CALL_PHONE"/>
** 寫好布局,包括電話號碼、開始暫停按鈕和提示 **
<?xml version="1.0" encoding="utf-8"?>
<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="wrap_content"
android:orientation="vertical"
android:gravity="center_horizontal"
tools:context="top.glimpse.constantcall.MainActivity">
<EditText
android:id="@+id/phonenumber"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="電話號碼"/>
<Button
android:id="@+id/btn_call"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="開始"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="設定:一分鐘打一次" />
</LinearLayout>
** 連續(xù)撥打電話的處理 **
撥打電話的代碼就兩行。
Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + number));
startActivity(intent);
但是要處理一下開始和停止的邏輯。這里把連續(xù)撥打電話的邏輯放在線程里,點擊了開始按鈕的時候就開始走連續(xù)撥打電話的邏輯,使用全局變量isCall來控制線程的結束。當用戶點擊停止的時候,破壞掉循環(huán),線程死掉。再次點擊開始的時候,再次啟動一個連續(xù)撥打線程。
代碼全在下面。
public class MainActivity extends AppCompatActivity {
private boolean isCall = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button btn_call = (Button) findViewById(R.id.btn_call);
btn_call.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
isCall = !isCall;
btn_call.setText(isCall ? "停止" : "開始");
if (isCall) {
new Thread(new Runnable() {
@Override
public void run() {
constantCall();
}
}).start();
}
}
});
}
private void constantCall() {
EditText et_phonenumber = (EditText) findViewById(R.id.phonenumber);
String number = et_phonenumber.getText().toString();
//用intent啟動撥打電話
while(isCall) {
if (!number.equals("")) {
Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + number));
startActivity(intent);
}
try {
Thread.sleep(1000 * 60);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
最后
好吧,是一個用幾行代碼寫出來的有點意思的東西。當然,后來跟女朋友說起這件事的時候,女朋友笑著說,程序員真可怕。
歡迎關注【Funny新青年】微信公眾號~