2016-04-05 11:25:56 lxj1137800599 阅读数 1155
  • S5PV210的时钟系统-1.6.ARM裸机第六部分

    本期课程主要讲述S5PV210的时钟系统,通过8节课的讲解和实战,希望大家能够彻底掌握S5PV210(以及类似复杂度的SoC)的时钟体系结构,理解MUX开关、DIV分频器、PLL倍频锁相工作电路等在时钟设置中的作用。

    7502 人正在学习 去看看 朱有鹏

近几天做了个多功能时钟,分享一下
主界面
这里写图片描述
对应的代码:
MainActivity.java

package com.example.clock;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TabHost;

public class MainActivity extends Activity {
    private TabHost tabHost;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        tabHost = (TabHost) findViewById(android.R.id.tabhost);
        tabHost.setup();
        // Call setup() before adding tabs if loading TabHost using
        // findViewById().
        // However: You do not need to call setup() after getTabHost() in
        // TabActivity.

        tabHost.addTab(tabHost.newTabSpec("tabTime").setIndicator("时钟")
                .setContent(R.id.tabTime));
        tabHost.addTab(tabHost.newTabSpec("tabAlarm").setIndicator("闹钟")
                .setContent(R.id.tabAlarm));
        tabHost.addTab(tabHost.newTabSpec("tabTimer").setIndicator("计时器")
                .setContent(R.id.tabTimer));
        tabHost.addTab(tabHost.newTabSpec("tabStopWatch").setIndicator("秒表")
                .setContent(R.id.tabStopWatch));
    }
}

时钟界面

TabTime.java

package com.example.clock;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.widget.LinearLayout;
import android.widget.TextView;

//tabtime就显示系统时间,注释部分表示是否在当前页面,如果在就发送message,不在就不发送
//有没有其实无所谓
public class TabTime extends LinearLayout {
    private TextView tvTime;
    private Handler myHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            tvTime.setText(new SimpleDateFormat("HH:mm:ss", Locale.CHINA)
                    .format(new Date()));
            //if (getVisibility() == View.VISIBLE) {
                myHandler.sendEmptyMessage(0);
            //}
        }
    };

    public TabTime(Context context) {
        super(context);
    }

    public TabTime(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public TabTime(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();

        tvTime = (TextView) findViewById(R.id.tvTime);
        myHandler.sendEmptyMessage(0);
    }

//  @Override
//  protected void onVisibilityChanged(View changedView, int visibility) {
//      super.onVisibilityChanged(changedView, visibility);
//
//      if (visibility == View.VISIBLE) {
//          myHandler.sendEmptyMessage(0);
//      } else {
//          myHandler.removeMessages(0);
//      }
//  }
}

闹钟界面:

这里写图片描述
对应代码:
TabAlarm.java

package com.example.clock;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.SystemClock;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TimePicker;

import com.example.clock.tool.AlarmReceiver;
import com.example.clock.tool.MyTimePickerDialog;

//闹钟功能
public class TabAlarm extends LinearLayout {
    private Button btn_add;
    private ListView listView;

    // 自定义数据类型用于adapter
    private class AlarmData {
        private long time;
        private Date date;

        public AlarmData(long time) {
            this.time = time;
            date = new Date(time);
        }

        public long getTime() {
            return time;
        }

        public String getTimeLabel() {
            return new SimpleDateFormat("MM-dd HH:mm", Locale.CHINA)
                    .format(date);
        }

        @Override
        public String toString() {
            return getTimeLabel();
        }
    };

    private ArrayAdapter<AlarmData> adapter;
    private AlarmManager alarmManager;

    public TabAlarm(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init();
    }

    public TabAlarm(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public TabAlarm(Context context) {
        super(context);
        init();
    }

    private void init() {
        alarmManager = (AlarmManager) getContext().getSystemService(
                Context.ALARM_SERVICE);
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();

        btn_add = (Button) findViewById(R.id.btn_add);
        listView = (ListView) findViewById(R.id.lvAlarmList);
        adapter = new ArrayAdapter<TabAlarm.AlarmData>(getContext(),
                android.R.layout.simple_list_item_1);
        listView.setAdapter(adapter);
        readAlarmList();

        btn_add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                addAlarm();
            }
        });
        // btn用来增加闹钟,listview的长按事件用来删除闹钟
        listView.setOnItemLongClickListener(new OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view,
                    final int position, long id) {
                new AlertDialog.Builder(getContext())
                        .setTitle("操作选项")
                        .setItems(new CharSequence[] { "删除" },
                                new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog,
                                            int which) {
                                        switch (which) {
                                        case 0:
                                            adapter.remove(adapter
                                                    .getItem(position));
                                            saveAlarmList();
                                            break;
                                        }
                                    }
                                }).setNegativeButton("取消", null).show();
                return true;
            }
        });
    }

    private void addAlarm() {
        Calendar calendar = Calendar.getInstance();
        new MyTimePickerDialog(getContext(), new OnTimeSetListener() {
            @Override
            public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                Calendar c = Calendar.getInstance();
                c.set(Calendar.HOUR_OF_DAY, hourOfDay);
                c.set(Calendar.MINUTE, minute);

                Calendar currentCalendar = Calendar.getInstance();
                if (c.getTimeInMillis() <= currentCalendar.getTimeInMillis()) {
                    c.setTimeInMillis(currentCalendar.getTimeInMillis() + 24
                            * 60 * 60 * 1000);
                }
                adapter.add(new AlarmData(c.getTimeInMillis()));
                saveAlarmList();
                // 使用TimePickerDialog时,点击对话框的确定按钮,会添加两条数据,
                // 原因是OnTimeSetListener中的onTimeSet()执行了两次,
                // 点击确定按钮时执行一次,
                // 对话框取消时,TimePickerDialog的onStop()方法中也执行了一次。
                // 解决方法:重写TimePickerDialog类,并覆盖onStop()
                // 在com.example.clock.tool包中
                alarmManager.setExact(AlarmManager.RTC_WAKEUP, SystemClock
                        .elapsedRealtime(), PendingIntent.getBroadcast(
                        getContext(), 0, new Intent(getContext(),
                                AlarmReceiver.class), 0));
                // setRepeating在API19以后不再准确,我试了好多种组合都不行
            }
        }, calendar.get(Calendar.HOUR_OF_DAY), calendar.get(Calendar.MINUTE),
                true).show();
    }

    private void saveAlarmList() {
        Editor editor = getContext().getSharedPreferences(
                TabAlarm.class.getName(), Context.MODE_PRIVATE).edit();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < adapter.getCount(); i++) {
            sb.append(adapter.getItem(i).getTime()).append(",");
        }//每条记录用逗号隔开
        String content = "";
        if (!sb.toString().equals("")) {
            content = sb.toString().substring(0, sb.length() - 1);
        }
        editor.putString("AlarmList", content);
        Log.i("record", content);
        editor.commit();
    }

    private void readAlarmList() {
        SharedPreferences sp = getContext().getSharedPreferences(
                TabAlarm.class.getName(), Context.MODE_PRIVATE);
        String content = sp.getString("AlarmList", null);

        if (!content.equals("")) {
            String[] timeString = content.split(",");
            for (String string : timeString) {
                adapter.add(new AlarmData(Long.parseLong(string)));
            }
        }
    }
}

里面还有一个BroadcastReceiver需要注册

package com.example.clock.tool;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

public class AlarmReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Toast.makeText(context, "闹铃响了", Toast.LENGTH_SHORT).show();
    }
}

以及重写的MyTimePickerDialog.java

package com.example.clock.tool;

import android.app.TimePickerDialog;
import android.content.Context;

public class MyTimePickerDialog extends TimePickerDialog {

    public MyTimePickerDialog(Context context, OnTimeSetListener callBack,
            int hourOfDay, int minute, boolean is24HourView) {
        super(context, callBack, hourOfDay, minute, is24HourView);
    }

    public MyTimePickerDialog(Context context, int theme,
            OnTimeSetListener callBack, int hourOfDay, int minute,
            boolean is24HourView) {
        super(context, theme, callBack, hourOfDay, minute, is24HourView);
    }

    @Override
    protected void onStop() {
        // 注释掉,防止onTimeSet()执行两次
        // super.onStop();
    }
}

计时器界面

这里写图片描述
TabTimer.java

package com.example.clock;

import android.content.Context;
import android.os.CountDownTimer;
import android.util.AttributeSet;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;

//计时器功能
public class TabTimer extends LinearLayout {
    private Spinner spinner;
    private TextView tv;
    private ArrayAdapter<CharSequence> adapter;
    private long tempMillis, defaultMillis;
    private Button btn1, btn2;
    private MyCount mCount;

    public TabTimer(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    public TabTimer(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public TabTimer(Context context) {
        super(context);
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();

        tv = (TextView) findViewById(R.id.tvShowTime);
        btn1 = (Button) findViewById(R.id.button1);
        btn2 = (Button) findViewById(R.id.button2);

        spinner = (Spinner) findViewById(R.id.spinner1);
        adapter = ArrayAdapter.createFromResource(getContext(), R.array.time,
                android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapter);

        final long[] arrayTime = {30*1000, 1*60*1000, 2*60*1000, 5*60*1000};
        spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view,
                    int pos, long id) {
                tempMillis = arrayTime[pos];
                defaultMillis = tempMillis;
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                tempMillis = arrayTime[0];// 默认30s
                defaultMillis = tempMillis;
            }
        });
        //spinner获取时间,后面两个button操作整个自定义计时器
        //逻辑虽然简单,但比较复杂。我调试了好一会儿
        btn1.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (btn1.getText().toString()
                        .equals(getResources().getString(R.string.start))) {
                    //点击开始按钮
                    mCount = new MyCount(tempMillis, 1000);
                    mCount.start();
                    btn2.setEnabled(true);
                    btn1.setText(getResources().getString(R.string.quit));
                } else if (btn1.getText().toString()
                        .equals(getResources().getString(R.string.quit))) {
                    //点击取消按钮
                    mCount.cancel();
                    btn2.setEnabled(false);
                    btn1.setText(getResources().getString(R.string.start));
                    tv.setText("");
                    btn2.setText(getResources().getString(R.string.pause));
                    tempMillis = defaultMillis;
                }
            }
        });
        btn2.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (btn2.getText().toString()
                        .equals(getResources().getString(R.string.pause))) {
                    //点击暂停按钮
                    mCount.cancel();
                    btn2.setText(getResources().getString(R.string.continu));
                } else if (btn2.getText().toString()
                        .equals(getResources().getString(R.string.continu))) {
                    //点击继续按钮
                    btn2.setText(getResources().getString(R.string.pause));
                    mCount = new MyCount(tempMillis, 1000);
                    mCount.start();
                }
            }
        });
    }

    //自定义计时器。网上说cancel失效,但我试了一下可行
    //用法比较简单,网上或者API上都有
    class MyCount extends CountDownTimer {
        public MyCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onFinish() {
            tv.setText("计时结束!");
        }

        @Override
        public void onTick(long millisUntilFinished) {
            tv.setText("剩余" + millisUntilFinished / 1000 + "秒。。。");
            tempMillis = millisUntilFinished;
        }
    }
}

秒表界面:

这里写图片描述
TabStopWatch.java

package com.example.clock;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.example.clock.tool.MyDataFormat;

//秒表功能
//网上的方法大多只有精确到秒,显然精度不够
//而且都是用的sendMessageDelayed方法,可能会不准
//我用的是系统时间,然后加以转化
public class TabStopWatch extends LinearLayout {
    private Button btn_start, btn_reset;
    private TextView single, total;
    private ListView timeCount;
    private ArrayAdapter<String> adapter;
    private long single_start, total_start;
    private int count;// adapter中的显示条目的计数器
    private boolean isReset, isPause;// 是否重置和暂停

    public TabStopWatch(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    public TabStopWatch(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public TabStopWatch(Context context) {
        super(context);
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();

        single = (TextView) findViewById(R.id.single);
        total = (TextView) findViewById(R.id.total);
        btn_start = (Button) findViewById(R.id.btn_start);
        btn_reset = (Button) findViewById(R.id.btn_reset);
        timeCount = (ListView) findViewById(R.id.timeCount);
        adapter = new ArrayAdapter<String>(getContext(),
                android.R.layout.simple_list_item_1);
        timeCount.setAdapter(adapter);
        single.setText("00:00.00");
        total.setText("00:00.00");

        btn_start.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (btn_start.getText().toString()
                        .equals(getResources().getString(R.string.start))) {
                    // 点击开始按钮
                    isReset = false;
                    isPause = false;
                    count = 0;
                    btn_start.setText(getResources().getString(R.string.pause));
                    btn_reset.setEnabled(true);

                    // 如果是第一次启动,formatLong返回0,
                    // 如果是暂停后启动,返回的是系统时间减去textview显示的时间
                    single_start = System.currentTimeMillis()
                            - MyDataFormat.formatLong(single.getText()
                                    .toString());
                    total_start = System.currentTimeMillis()
                            - MyDataFormat.formatLong(total.getText()
                                    .toString());
                    // 获取时间
                    singleTextTime();
                    totalTextTime();
                } else if (btn_start.getText().toString()
                        .equals(getResources().getString(R.string.pause))) {
                    // 点击停止按钮
                    isPause = true;
                    btn_start.setText(getResources().getString(R.string.start));
                    btn_reset.setText(getResources().getString(R.string.reset));
                }
            }
        });

        btn_reset.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (btn_reset.getText().toString()
                        .equals(getResources().getString(R.string.count))) {
                    // 点击计次按钮
                    adapter.add("计数:" + count++ + "     "
                            + single.getText().toString());
                    single.setText("00:00.00");
                    single_start = System.currentTimeMillis();
                    singleTextTime();
                } else if (btn_reset.getText().toString()
                        .equals(getResources().getString(R.string.reset))) {
                    // 点击复位按钮
                    adapter.clear();
                    single.setText("00:00.00");
                    total.setText("00:00.00");
                    btn_reset.setEnabled(false);
                    isReset = true;
                    btn_reset.setText(getResources().getString(R.string.count));
                }
            }
        });
    }

    private Handler myHandler = new Handler() {
        public void handleMessage(Message msg) {
            if (msg.what == 1) {
                if (!isPause && !isReset) {
                    single.setText(MyDataFormat.format(
                            System.currentTimeMillis(), single_start));
                    myHandler.sendEmptyMessage(1);
                }
            } else if (msg.what == 2) {
                if (!isPause && !isReset) {
                    total.setText(MyDataFormat.format(
                            System.currentTimeMillis(), total_start));
                    myHandler.sendEmptyMessage(2);
                }
            }
        };
    };
    private void singleTextTime() {
        myHandler.sendEmptyMessage(1);
    }

    private void totalTextTime() {
        myHandler.sendEmptyMessage(2);
    }
}

这里需要用到工具类

package com.example.clock.tool;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class MyDataFormat {
    // 把时间差的"00:00:000"格式变为"00:00.00"
    public static String format(long data, long ori) {
        String temp = new SimpleDateFormat("mm:ss:SSS", Locale.CHINA)
                .format(data - ori);
        int position = temp.lastIndexOf(":");
        return temp.substring(0, position) + "."
                + temp.substring(position + 1, temp.length() - 1);
    }

    // 把string的"00:00.00"格式变为long类型
    public static long formatLong(String data){
        int position = data.lastIndexOf(".");
        data = data.substring(0, position) + ":"
                + data.substring(position + 1, data.length() - 1);
        SimpleDateFormat sdf = new SimpleDateFormat("mm:ss:SSS", Locale.CHINA);
        Date date = null;
        try {
            date = sdf.parse(data);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date.getTime();
    }
}

最后贴一些资源和布局文件吧:
main.xml

<LinearLayout xmlns:tools="http://schemas.android.com/tools"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.example.clock.MainActivity" >

    <TabHost
        android:id="@android:id/tabhost"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical" >

            <TabWidget
                android:id="@android:id/tabs"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" >
            </TabWidget>

            <FrameLayout
                android:id="@android:id/tabcontent"
                android:layout_width="match_parent"
                android:layout_height="match_parent" >

                <com.example.clock.TabTime
                    android:id="@+id/tabTime"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:orientation="vertical" >

                    <TextView
                        android:id="@+id/tvTime"
                        android:layout_width="match_parent"
                        android:layout_height="match_parent"
                        android:gravity="center"
                        android:textAppearance="?android:attr/textAppearanceLarge" />
                </com.example.clock.TabTime>

                <com.example.clock.TabAlarm
                    android:id="@+id/tabAlarm"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:orientation="vertical" >

                    <Button
                        android:id="@+id/btn_add"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_gravity="top|center"
                        android:text="@string/addAlarm" />

                    <ListView
                        android:id="@+id/lvAlarmList"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content" >
                    </ListView>
                </com.example.clock.TabAlarm>

                <com.example.clock.TabTimer
                    android:id="@+id/tabTimer"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:orientation="vertical" >

                    <Spinner
                        android:id="@+id/spinner1"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_gravity="center" />

                    <TextView
                        android:id="@+id/tvShowTime"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:enabled="false"
                        android:gravity="center"
                        android:textSize="30sp" />

                    <Button
                        android:id="@+id/button1"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_gravity="center"
                        android:text="@string/start" />

                    <Button
                        android:id="@+id/button2"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_gravity="center"
                        android:enabled="false"
                        android:text="@string/pause" />
                </com.example.clock.TabTimer>

                <com.example.clock.TabStopWatch
                    android:id="@+id/tabStopWatch"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:orientation="vertical" >

                    <TextView
                        android:id="@+id/single"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:gravity="right"
                        android:textSize="15sp" />

                    <TextView
                        android:id="@+id/total"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:gravity="right"
                        android:textSize="30sp" />

                    <LinearLayout
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:orientation="horizontal" >

                        <Button
                            android:id="@+id/btn_start"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_gravity="center"
                            android:text="@string/start" />

                        <Button
                            android:id="@+id/btn_reset"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_gravity="center"
                            android:enabled="false"
                            android:text="@string/count" />
                    </LinearLayout>

                    <ListView
                        android:id="@+id/timeCount"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content" >
                    </ListView>
                </com.example.clock.TabStopWatch>
            </FrameLayout>
        </LinearLayout>
    </TabHost>

</LinearLayout>

strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">Clock</string>
    <string name="addAlarm">添加闹钟</string>
    <string name="start">开始</string>
    <string name="pause">暂停</string>
    <string name="quit">取消</string>
    <string name="continu">继续</string>

    <string name="count">计次</string>
    <string name="reset">复位</string>

</resources>

arrays.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string-array name="time">
        <item>30秒</item>
        <item>1分钟</item>
        <item>2分钟</item>
        <item>5分钟</item>
    </string-array>

</resources>
2016-07-23 17:43:36 sdsfs443 阅读数 1657
  • S5PV210的时钟系统-1.6.ARM裸机第六部分

    本期课程主要讲述S5PV210的时钟系统,通过8节课的讲解和实战,希望大家能够彻底掌握S5PV210(以及类似复杂度的SoC)的时钟体系结构,理解MUX开关、DIV分频器、PLL倍频锁相工作电路等在时钟设置中的作用。

    7502 人正在学习 去看看 朱有鹏

新建项目,在layout中添加tabhost组件:

<?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="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:orientation="vertical"
    tools:context="com.example.jowang.clock.MainActivity">


    <TabHost
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/tabHost"
        android:layout_gravity="center_horizontal">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">

            <TabWidget
                android:id="@android:id/tabs"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"></TabWidget>

            <FrameLayout
                android:id="@android:id/tabcontent"
                android:layout_width="match_parent"
                android:layout_height="match_parent">

                <LinearLayout
                    android:id="@+id/tabTime"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:orientation="vertical"></LinearLayout>

                <LinearLayout
                    android:id="@+id/tabAlarm"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:orientation="vertical"></LinearLayout>

                <LinearLayout
                    android:id="@+id/tabTimer"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:orientation="vertical"></LinearLayout>
                <LinearLayout
                    android:id="@+id/tabStopwatch"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:orientation="vertical"></LinearLayout>
            </FrameLayout>
        </LinearLayout>
    </TabHost>
</LinearLayout>
在mainactivity中写入代码:

public class MainActivity extends AppCompatActivity {
    private TabHost tabHost;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tabHost=(TabHost)findViewById(R.id.tabHost);
        tabHost.setup();
        tabHost.addTab(tabHost.newTabSpec("tabTime").setIndicator("时钟").setContent(R.id.tabTime));
        tabHost.addTab(tabHost.newTabSpec("tabAlarm").setIndicator("闹钟").setContent(R.id.tabAlarm));
        tabHost.addTab(tabHost.newTabSpec("tabTimer").setIndicator("计时器").setContent(R.id.tabTimer));
        tabHost.addTab(tabHost.newTabSpec("tabStopwatch").setIndicator("秒表").setContent(R.id.tabStopwatch));

    }
}

2016-07-23 19:21:22 sdsfs443 阅读数 561
  • S5PV210的时钟系统-1.6.ARM裸机第六部分

    本期课程主要讲述S5PV210的时钟系统,通过8节课的讲解和实战,希望大家能够彻底掌握S5PV210(以及类似复杂度的SoC)的时钟体系结构,理解MUX开关、DIV分频器、PLL倍频锁相工作电路等在时钟设置中的作用。

    7502 人正在学习 去看看 朱有鹏

第一步:

新建timeview class,extends linearlayout:

public class TimeView extends LinearLayout {
    private TextView textView;
    public TimeView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public TimeView(Context context) {
        super(context);
    }

    public TimeView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        textView=(TextView)findViewById(R.id.time);
        handler.sendEmptyMessage(0);
    }

    @Override
    protected void onVisibilityChanged(View changedView, int visibility) {
        super.onVisibilityChanged(changedView, visibility);
        if (visibility==changedView.VISIBLE){
            handler.sendEmptyMessage(0);

        }else {
            handler.removeMessages(0);
        }
    }


    private void refreshtime(){
        java.util.Calendar c= java.util.Calendar.getInstance();
        textView.setText(String.format("%d:%d:%d",c.get(java.util.Calendar.HOUR_OF_DAY),c.get(java.util.Calendar.MINUTE),c.get(java.util.Calendar.SECOND)));
    }

    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            refreshtime();
            if (getVisibility()== View.VISIBLE){

                sendEmptyMessageDelayed(0,1000);
            }
        }
    };
}
替换layout中的第一个tabhost,此时layout代码如下:

<?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="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:orientation="vertical"
    tools:context="com.example.jowang.clock.MainActivity">


    <TabHost
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/tabHost"
        android:layout_gravity="center_horizontal">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical"
            >

            <TabWidget
                android:id="@android:id/tabs"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"></TabWidget>

            <FrameLayout
                android:id="@android:id/tabcontent"
                android:layout_width="match_parent"
                android:layout_height="match_parent">

                <com.example.jowang.clock.TimeView
                    android:id="@+id/tabTime"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:orientation="vertical">
                    <TextView
                        android:layout_width="match_parent"
                        android:layout_height="match_parent"
                        android:id="@+id/time"
                        android:textAppearance="?android:attr/textAppearanceLarge"
                        android:gravity="center"

                        />
                </com.example.jowang.clock.TimeView>

                <LinearLayout
                    android:id="@+id/tabAlarm"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:orientation="vertical"></LinearLayout>

                <LinearLayout
                    android:id="@+id/tabTimer"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:orientation="vertical"></LinearLayout>
                <LinearLayout
                    android:id="@+id/tabStopwatch"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:orientation="vertical"></LinearLayout>
            </FrameLayout>
        </LinearLayout>
    </TabHost>
</LinearLayout>

2019-12-20 23:37:20 qq_44138925 阅读数 150
  • S5PV210的时钟系统-1.6.ARM裸机第六部分

    本期课程主要讲述S5PV210的时钟系统,通过8节课的讲解和实战,希望大家能够彻底掌握S5PV210(以及类似复杂度的SoC)的时钟体系结构,理解MUX开关、DIV分频器、PLL倍频锁相工作电路等在时钟设置中的作用。

    7502 人正在学习 去看看 朱有鹏

多功能闹钟App

简 介

此多功能闹钟界面采用TabHost框架,头部包含分别用LinearLayout水平布局显示四个标签闹钟,时钟,计时器和秒表,FrameLayout框架内部采用LinearLayout垂直布局。功能事件的基本实现分别有AlarmView类,AlarmReceiver类,PlayAlarmAty类, TimeView类和StopWatch类完成。

主 要 技 术

此多功能闹钟界面采用TabHost 框架,头部包含分别用LinearLayout水平布局显示四个标签闹钟,时钟,计时器和秒表,FrameLayout框架内部采用LinearLayout垂直布局。功能事件的基本实现分别有AlarmView类,AlarmReceiver类,PlayAlarmAty类, TimeView类和StopWatch类完成。:

  1. 闹钟界面的界面设计 ,闹钟界面使用一个Button按钮和ListvView,设置的闹钟由ListView的Item项来呈现出来;开始按钮设置监听,当点击添加闹钟按钮时触发按钮监听引用TimePickerDialog将弹出一个设置时间对话框,当设置时间后点击ok按钮将触发监听中添加saveAlarmList()存储方法保存数据;闹钟功能使用SharedPreferences类存取数据,使用创建的saveAlarmList()存储方法和readSavedAlarmList()读取方法来实现闹钟设定数据的存取,使用创建AlarmData工具类进行数据存放。闹钟的设置及具体的响应采用AlarmView类,AlarmReceiver类和PlayAlarmAty类;AlarmView类中通过listview的setOnItemLongClickListener方法监听每个Item项,当检测到长按水平弹出到闹钟的操作对话框,通过弹出对话框中setNegativeButton按钮,删除Item项目闹钟;闹钟响铃通过AlarmManager的实例对象,根据我们设定时间来实现响铃。该闹钟是利用了页面跳转来实现的响铃,通过getActivity()方法来获取PendingIntent对象,将设定好的时间通过数据跳转到响铃的页面,通过弹出一个提示对话框和mediaPlayer 组件播放音乐来实现响铃功能。
  2. 时钟功能的实现简单引用了DigitalClock 显示时钟时间。
  3. 计时器功能具体实现是通过TimerView类来实现的,类中设置了开始,暂停和重置方法,然后监听开始,暂停,重置按钮来引用对应方法来实现计时器的计时功能,计时时间到采用Handle机制来新建一个对话框提醒时间到。
  4. 秒表的具体实现通过StopWatch 类来实现,类中设置了开始,暂停,复位和重置按钮的监听,监听直接引用了Chronometer 的start,stop,setBase和setFormat等方法实现秒表的功能。

界面截图

在这里插入图片描述

主要代码

页面,MainActivity 代码.

// An highlighted block
public class MainActivity extends Activity {
    private TabHost tabHost;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        tabHost=(TabHost)findViewById(android.R.id.tabhost);
        tabHost.setup();

        tabHost.addTab(tabHost.newTabSpec("tabAlarm").setIndicator("闹钟").setContent(R.id.tabAlarm));
        tabHost.addTab(tabHost.newTabSpec("tabTime").setIndicator("时钟").setContent(R.id.tabTime));
        tabHost.addTab(tabHost.newTabSpec("tabTimer").setIndicator("计时器").setContent(R.id.tabTimer));
        tabHost.addTab(tabHost.newTabSpec("tabStopWatch").setIndicator("秒表").setContent(R.id.tabStopWatch));
    }
}

页面,PlayAlarmAty 代码.

// An highlighted block
public class PlayAlarmAty extends Activity {
    private MediaPlayer mp;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mp = MediaPlayer.create(this,R.raw.clockmusic2);
        mp.start();
        new AlertDialog.Builder(PlayAlarmAty.this)
                .setIcon(R.mipmap.ic_launcher)
                .setTitle("闹钟")
                .setMessage("快完成你制定的计划吧!!!")
                .setNegativeButton("关闭", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        PlayAlarmAty.this.finish();
                        mp.stop();
                    }
                })
                .show();
    }
    @Override
    protected void onPause(){
        super.onPause();
        finish();
    }
    protected void onDestroy(){
        super.onDestroy();
        mp.stop();
        mp.release();
    }
}

页面,AlarmView 代码.

// An highlighted block
public class AlarmView extends LinearLayout {

    public AlarmView(Context context,AttributeSet attrs,int defStyle){
        super(context,attrs,defStyle);
        init();
    }
    public AlarmView(Context context,AttributeSet attrs){
        super(context,attrs);
        init();
    }
    public AlarmView(Context context ){
        super(context);
        init();
    }
    private void init(){
        alarmManager= (AlarmManager) getContext().getSystemService(Context.ALARM_SERVICE);
    }

    @Override
    protected void onFinishInflate(){
        super.onFinishInflate();

        btAddAlarm=(Button) findViewById(R.id.btnAddAlarm);
        lvAlarmList=(ListView) findViewById(R.id.lvAlarmList);

        adapter=new ArrayAdapter<AlarmData>(getContext(),android.R.layout.simple_list_item_1);
        lvAlarmList.setAdapter(adapter);
        readSavedAlarmList();

        btAddAlarm.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                addAlarm();
            }
        });

        lvAlarmList.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
                new AlertDialog.Builder(getContext()).setTitle("操作").setItems(new CharSequence[]{"删除"}, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        switch (which){
                            case 0:
                                deleteAlarm(position);
                                break;
                            default:
                                break;
                        }
                    }
                }).setNegativeButton("取消",null).show();
                return true;
            }
        });
    }

    private void deleteAlarm(int position){
        AlarmData ad=adapter.getItem(position);
        adapter.remove(ad);
        saveAlarmList();   alarmManager.cancel(PendingIntent.getBroadcast(getContext(),ad.getId(),new Intent(getContext(),AlarmReceiver.class),0));
    }

    private void addAlarm(){
        Calendar c =Calendar.getInstance();
        new TimePickerDialog(getContext(), new TimePickerDialog.OnTimeSetListener() {
            @Override
            public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                Calendar calendar=Calendar.getInstance();
                calendar.set(Calendar.HOUR_OF_DAY,hourOfDay);
                calendar.set(Calendar.MINUTE,minute);
                calendar.set(Calendar.SECOND,0);
                calendar.set(Calendar.MILLISECOND,0);

                Calendar currentTime=Calendar.getInstance();
                if (calendar.getTimeInMillis()<=currentTime.getTimeInMillis()){
                    calendar.setTimeInMillis(calendar.getTimeInMillis()+24*60*60*1000);
                }
                AlarmData ad=(new AlarmData(calendar.getTimeInMillis()));
                adapter.add(ad);
                alarmManager.set(AlarmManager.RTC_WAKEUP,
                        ad.getTime(),
                        PendingIntent.getBroadcast(getContext(),
                                ad.getId(),
                                new Intent(getContext(),AlarmReceiver.class),0));
                saveAlarmList();
            }
        },c.get(Calendar.HOUR_OF_DAY),c.get(Calendar.MINUTE),true).show();
    }
    private void saveAlarmList(){
        SharedPreferences.Editor editor =getContext().getSharedPreferences(AlarmView.class.getName(),Context.MODE_PRIVATE).edit();

        StringBuffer sb = new StringBuffer();
        for (int i=0;i<adapter.getCount();++i) {
            sb.append(adapter.getItem(i).getTime()).append(",");
        }
        if(sb.length()>1) {
            String content = sb.toString().substring(0, sb.length() - 1);
            editor.putString(KEY_ALARM_LIST, content);
            System.out.println(content);
        }else {
            editor.putString(KEY_ALARM_LIST,null);
        }
            editor.commit();
    }

    private void readSavedAlarmList(){
        SharedPreferences sp=getContext().getSharedPreferences(AlarmView.class.getName(),Context.MODE_PRIVATE);
        String content=sp.getString(KEY_ALARM_LIST,null);
        if (content!=null){
            String[] timeString=content.split(",");
            for (String string:timeString){
                adapter.add(new AlarmData(Long.parseLong(string)));
            }
        }
    }
    private static final String KEY_ALARM_LIST="alarmlist";
    private Button btAddAlarm;
    private ListView lvAlarmList;
    private ArrayAdapter<AlarmData> adapter;
    private AlarmManager alarmManager;
    private static class AlarmData{
        public AlarmData(long time){
            this.time=time;
            date=Calendar.getInstance();
            date.setTimeInMillis(time);

            timeLable=String.format("%d月%d日 %d:%d",
                   date.get(Calendar.MONTH)+1,
                   date.get(Calendar.DAY_OF_MONTH),
                   date.get(Calendar.HOUR_OF_DAY),
                   date.get(Calendar.MINUTE));

        }
        public long getTime(){
            return time;
        }
        public String getTimeLable(){
            return timeLable;
        }
        @Override
        public String toString(){
            return getTimeLable();
        }
        public  int getId() {
            return  (int)(getTime()/1000/60);
        }
        private  String timeLable="";
        private long time=0;
        private Calendar date;
    }
}

计时器页面,TimerView 代码.

// An highlighted block
public class TimerView extends LinearLayout{
    private Button btnStart, btnPause, btnReset;
    private EditText etHour, etMin, etSec;
    private Timer timer = new Timer ( );
    private TimerTask timerTask = null;
    private int allTimerCount = 0;
    private static final int MSG_WHAT_TIME_IS_UP = 1;
    private static final int MSG_WHAT_TIME_TICK = 2;
    
    public TimerView(Context context , @Nullable AttributeSet attrs , int defStyleAttr) {
        super ( context , attrs , defStyleAttr );
    }
    public TimerView(Context context , @Nullable AttributeSet attrs) {
        super ( context , attrs );
    }
    public TimerView(Context context) {
        super ( context );
    }
    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();

        btnPause = (Button) findViewById(R.id.btnPause);
        btnPause.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                stopTimer();
                btnPause.setVisibility(View.GONE);
                btnStart.setVisibility ( View.VISIBLE );
                btnReset.setVisibility(View.VISIBLE);
            }
        });
        btnReset = (Button) findViewById(R.id.btnReset);
        btnReset.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                stopTimer();
                etHour.setText("0");
                etMin.setText("0");
                etSec.setText("0");

                btnReset.setVisibility(View.GONE);
                btnPause.setVisibility(View.GONE);
                btnStart.setVisibility(View.VISIBLE);
            }
        });
        btnStart = (Button) findViewById(R.id.btnStart);
        btnStart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startTimer();

                btnStart.setVisibility(View.GONE);
                btnPause.setVisibility(View.VISIBLE);
                btnReset.setVisibility(View.VISIBLE);
            }
        });

        etHour = (EditText) findViewById(R.id.etHour);
        etMin = (EditText) findViewById(R.id.etMin);
        etSec = (EditText) findViewById(R.id.etSec);
        etHour.setText("00");
        etHour.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (!TextUtils.isEmpty(s)) {
                    int value = Integer.parseInt(s.toString());
                    if (value>59) {
                        etHour.setText("59");
                    }else if (value<0) {
                        etHour.setText("0");
                    }
                }
                checkToEnableBenStart ();
            }
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,int after) {
            }
            @Override
            public void afterTextChanged(Editable s) {
            }
        });
        etMin.setText("00");
        etMin.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (!TextUtils.isEmpty(s)) {
                    int value = Integer.parseInt(s.toString());

                    if (value>59) {
                        etMin.setText("59");
                    }else if (value<0) {
                        etMin.setText("0");
                    }
                }
                checkToEnableBenStart ();
            }
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,int after) {
            }
            @Override
            public void afterTextChanged(Editable s) {
            }
        });
        etSec.setText("00");
        etSec.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (!TextUtils.isEmpty(s)) {
                    int value = Integer.parseInt(s.toString());
                    if (value>59) {
                        etSec.setText("59");
                    }else if (value<0) {
                        etSec.setText("0");
                    }
                }
                checkToEnableBenStart ();
            }
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,int after) {
            }
            @Override
            public void afterTextChanged(Editable s) {
            }
        });

        btnStart.setVisibility(View.VISIBLE);
        btnStart.setEnabled(false);
        btnPause.setVisibility(View.GONE);
        btnReset.setVisibility(View.GONE);
    }
    private void checkToEnableBenStart() {
        btnStart.setEnabled ( (!TextUtils.isEmpty ( etHour.getText ( ) ) && Integer.parseInt ( etHour.getText ( ).toString ( ) ) > 0) ||
                (!TextUtils.isEmpty ( etMin.getText ( ) ) && Integer.parseInt ( etMin.getText ( ).toString ( ) ) > 0) ||
                (!TextUtils.isEmpty ( etSec.getText ( ) ) && Integer.parseInt ( etSec.getText ( ).toString ( ) ) > 0) );
    }
    private void startTimer() {
        allTimerCount = Integer.parseInt ( etHour.getText ( ).toString ( ) ) * 60 * 60 + Integer.parseInt ( etMin.getText ( ).toString ( ) ) * 60 + Integer.parseInt ( etSec.getText ( ).toString ( ) );
        if (timerTask == null) {
            timerTask = new TimerTask ( ) {
                @Override
                public void run() {
                    allTimerCount--;
                    handler.sendEmptyMessage ( MSG_WHAT_TIME_TICK );
                    if (allTimerCount == 0) {
                        handler.sendEmptyMessage ( MSG_WHAT_TIME_IS_UP );
                        stopTimer ( );
                    }
                }
            };
            timer.schedule ( timerTask , 1000 , 1000 );
        }

    }
    
    private void stopTimer() {
        if (timerTask != null) {
            timer.cancel ( );
            timerTask = null;
        }
    }

    private android.os.Handler handler = new android.os.Handler ( ) {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case MSG_WHAT_TIME_TICK:
                    int hour = allTimerCount / 60 / 60;
                    int min = (allTimerCount / 60) % 60;
                    int sec = allTimerCount % 60;
                    etHour.setText ( hour + "" );
                    etMin.setText ( min + "" );
                    etSec.setText ( sec + "" );
                    break;

                case MSG_WHAT_TIME_IS_UP:
                    new AlertDialog.Builder ( getContext ( ) ).setTitle("Timer" )
                            .setMessage ( "时间到" )
                            .setNegativeButton ( "返回" , null )
                            .show ( );
                    btnStart.setVisibility ( View.VISIBLE );
                    btnPause.setVisibility ( View.GONE );
                    btnReset.setVisibility ( View.GONE );
                    break;
                default:
                    break;
            }
        }
    };  
}

秒表页面,StopWatch 代码.

// An highlighted block
public class StopWatch extends LinearLayout {

    private Chronometer myChronometer;
    private Button butStart;
    private Button butStop;
    private Button butResume;
    private Button butReset;

    public StopWatch(Context context , @Nullable AttributeSet attrs) {
        super ( context , attrs );

    }
    @Override
    protected void onFinishInflate() {
        super.onFinishInflate ( );
        
        myChronometer = (Chronometer) super.findViewById ( R.id.myChronometer );
        butStart = (Button) super.findViewById ( R.id.butStart );
        butStop = (Button) super.findViewById ( R.id.butPause );
        butResume=(Button) super.findViewById ( R.id.butResume );
        butReset = (Button) super.findViewById ( R.id.butReset );

        butStart.setVisibility ( View.VISIBLE );
        butStop.setVisibility ( View.GONE);
        butResume.setVisibility ( View.GONE);
        butReset.setVisibility ( View.GONE );
        
        butStart.setOnClickListener ( new OnClickListener ( ) {
            @Override
            public void onClick(View v) {
                myChronometer.setBase ( (long) ((long) (SystemClock.elapsedRealtime ()-
                        (long)Double.parseDouble (myChronometer.getText ().toString ().split ( ":")[0])*60*1000)-
                        (long)Double.parseDouble ( myChronometer.getText ().toString ().split (":" )[1] )*1000) );
                myChronometer.start ();
                butStart.setVisibility ( View.GONE );
                butResume.setVisibility ( View.VISIBLE );
                butStop.setVisibility ( View.VISIBLE);
                butReset.setVisibility ( View.GONE );
            }
        } );

        butStop.setOnClickListener ( new OnClickListener ( ) {
            @Override
            public void onClick(View v) {
                myChronometer.stop ();
                butStop.setVisibility ( View.GONE );
                butResume.setVisibility ( View.GONE);
                butStart.setVisibility ( View.VISIBLE );
                butReset.setVisibility ( View.VISIBLE );
            }
        } );

        butReset.setOnClickListener ( new OnClickListener ( ) {
            @Override
            public void onClick(View v) {
                myChronometer.setBase ( SystemClock.elapsedRealtime ( ) );
                butReset.setVisibility ( View.GONE );
                butResume.setVisibility ( View.GONE );
                butStart.setVisibility ( View.VISIBLE );
                butStop.setVisibility ( View.GONE);
            }
        } );

        butResume.setOnClickListener ( new OnClickListener ( ) {
            @Override
            public void onClick(View v) {
                myChronometer.setFormat ( "%s" );
                myChronometer.setBase ( SystemClock.elapsedRealtime ( ) );
                butStop.setVisibility ( View.VISIBLE );
                butReset.setVisibility ( View.GONE );
                butResume.setVisibility ( View.VISIBLE);
                butStart.setVisibility ( View.GONE );
            }
        } );
    }
}

源码链接

源码下载链接: link.

作者信息

E-mail
2261142446@qq.com
Authors
罄宇
2016-07-26 12:26:43 sdsfs443 阅读数 2480
  • S5PV210的时钟系统-1.6.ARM裸机第六部分

    本期课程主要讲述S5PV210的时钟系统,通过8节课的讲解和实战,希望大家能够彻底掌握S5PV210(以及类似复杂度的SoC)的时钟体系结构,理解MUX开关、DIV分频器、PLL倍频锁相工作电路等在时钟设置中的作用。

    7502 人正在学习 去看看 朱有鹏

这个闹钟程序已经学了第二遍,第一遍学了之后一切都很糊涂,这次再学终于有点清晰。

第一步:

新建alarm activity继承linearlayout,将对应ui换成:

<com.example.jowang.clock0726.Alarm
    android:id="@+id/linearLayout2"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    <ListView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/list1"
        android:layout_weight="1"
        ></ListView>
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/btn1"
        android:text="add"
        android:layout_gravity="center_horizontal"/>
</com.example.jowang.clock0726.Alarm>
可以看到有一个listview和一个button,listview的weight注明为1,这样按钮就会显示在屏幕底部。

第二步:

alarm activity代码如下:

public class Alarm extends LinearLayout {
    private Button button;
    private ListView listView;
    ArrayAdapter<Alarm.myalarm> adapter;
    public Alarm(Context context) {
        super(context);
    }
    public Alarm(Context context, AttributeSet attrs) {
        super(context, attrs);
    }
    public Alarm(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }
    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        button=(Button)findViewById(R.id.btn1);
        listView=(ListView)findViewById(R.id.list1);
        button.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                addAlarm();
            }
        });
    }
    public void addAlarm(){
        adapter=new ArrayAdapter<Alarm.myalarm>(getContext(),android.R.layout.simple_list_item_1);
        adapter.add(new myalarm(System.currentTimeMillis()));
        listView.setAdapter(adapter);
    }
    class myalarm{
        private Date date;
        private long time=0;
        private String timeLabel="";
        public myalarm(long time){
            this.time=time;
            date=new Date(time);
            timeLabel=date.getHours()+":"+date.getMinutes();
        }

        public long getTime() {
            return time;
        }

        public String getTimeLabe() {
            return timeLabel;
        }

        @Override
        public String toString() {
            return timeLabel;
        }
    }

}
此时初步实现显示闹钟

没有更多推荐了,返回首页