android---手电筒之摩尔斯电码

摩尔斯电码通过控制闪光灯的开关的持续时间,来发送点和横,这次写代码的过程中,学习到了分解的好处,把每一步细分,带来的是开发效率的提升,如下面代码.
    public static void sleep(int t) {
        try {
            Thread.sleep(t);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    private void sendot() {
        startflashlight();
        sleep(DOT_TIME);
        stopflashlight();
    }
    private void sendline() {
        startflashlight();
        sleep(LINE_TIME);
        stopflashlight();
    }

发送点,横,以及休眠专门都细分,这样在控制函数当中只要调用就好了

    public void sendmorsecode(View view) {

        if (!getPackageManager().hasSystemFeature(
                PackageManager.FEATURE_CAMERA_FLASH)) {
            Toast.makeText(this, "当前设备没有闪光灯", Toast.LENGTH_LONG).show();
            return;}
        String SOS = "...---...";
        char c;
        for (int i = 0; i < SOS.length(); i++) {
            if((c = SOS.charAt(i)) == '.'){
                sendot();
                sleep(DOT_LINE_TIME);
            }else {
                sendline();
                sleep(DOT_LINE_TIME);
            }
        }
        }

对应的xml布局文件

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/linearlayout_morsecode" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_marginTop="120dp" android:layout_marginLeft="40dp" android:layout_marginRight="40dp" android:orientation="vertical" android:visibility="gone" >

    <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="点击发送SOS求救新号" android:textColor="#FFF" android:gravity="center" android:textSize="30sp" />   
        <Button  android:layout_width="60dp" android:layout_height="60dp" android:layout_marginTop="20dp" android:background="@drawable/morse_send" android:layout_gravity="center" android:onClick="sendmorsecode" />

</LinearLayout>

你可能感兴趣的:(android---手电筒之摩尔斯电码)