有一次忘记是什么情况和女朋友闹了矛盾,女朋友就是不接我电话,当时我也有点不高兴不接我就一直打,打了半天还是不接。我就想啊,写个Android程序装在手机上自动打!

思路

当时说写马上就写出来了,因为这个的思路特别简单,就是写一个打电话的代码,然后让这段代码循环调用就好了。

实现

** 写好拨打电话的权限 **

** 写好布局,包括电话号码、开始暂停按钮和提示 **

xmlns:tools="http://schemas.android/tools"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:orientation="vertical"

android:gravity="center_horizontal"

tools:context="top.glimpse.constantcall.MainActivity">

android:id="@+id/phonenumber"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:hint="电话号码"/>

android:id="@+id/btn_call"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="开始"/>

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="设定:一分钟打一次" />

** 连续拨打电话的处理 **

拨打电话的代码就两行。

Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + number));

startActivity(intent);

但是要处理一下开始和停止的逻辑。这里把连续拨打电话的逻辑放在线程里,点击了开始按钮的时候就开始走连续拨打电话的逻辑,使用全局变量isCall来控制线程的结束。当用户点击停止的时候,破坏掉循环,线程死掉。再次点击开始的时候,再次启动一个连续拨打线程。

代码全在下面。

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新青年】微信公众号~

更多推荐

android+自动拨打电话,自动拨打电话 - 好玩的代码