当前位置:网站首页>安卓开发——服务应用,计时器的实现(线程+服务)

安卓开发——服务应用,计时器的实现(线程+服务)

2020-11-09 10:56:00 osc_t4xzns0d

实验题目

  1. 实现一个倒计时时钟,创建子线实现计时功能,使用异步消息机制将计时结果显示在界面上,如图,在文本框中输入数字(使用Number文本框),点击开始按钮后,下方文本框的数字每秒减1,点击停止即停止倒计时
  2. 创建ClockActivity,可输入一个时间,再创建一个ClockService在用于计时,到时间后,以在Activity中发出通知(在下方的TextView中显示“时间到”)。
    注意:这里涉及到了Service操作Activity

实验一

代码:

MainActivity :

public class MainActivity extends AppCompatActivity {
   
   
    boolean iswork;
    String number;
    EditText edtNumber;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
   
   
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button btnStart=(Button)findViewById(R.id.btnStart);
        Button btnStop=(Button)findViewById(R.id.btnStop);

        final Handler handler=new Handler(){
   
   
            public void handleMessage(Message msg){
   
   
                edtNumber=(EditText)findViewById(R.id.edtNumber);
                edtNumber.setText(String.valueOf(msg.what));
            }
        };

        btnStart.setOnClickListener(new View.OnClickListener() {
   
   
            @Override
            public void onClick(View v) {
   
   
                EditText edtCount=(EditText)findViewById(R.id.edtNumber);
                number=String.valueOf(edtCount.getText());
                iswork=true;
                new Thread(new Runnable() {
   
   
                    @Override
                    public void run() {
   
   
                        try {
   
   
                            for (int i=Integer.valueOf(number)-1;i>=0;i--){
   
   
                                if (iswork){
   
   
                                    //间隔一秒
                                    Thread.sleep(1000);
                                    Message msg=new Message();
                                    msg.what=i;
                                    handler.sendMessage(msg);
                                }
                            }
                        } catch (InterruptedException e) {
   
   
                            e.printStackTrace();
                        }

                    }
                }).start();
            }
        });
        btnStop.setOnClickListener(new View.OnClickListener() {
   
   
            @Override
            public void onClick(View v) {
   
   
                if (iswork){
   
   
                    //停止
                    iswork=false;
                }
            }
        });
    }

}
布局文件:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    xmlns:android="http://schemas.android.com/apk/res/android">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <Button
            android:layout_width="150dp"
            android:layout_marginLeft="15dp"
            android:layout_height="wrap_content"
            android:onClick="Camera_onClick"
            android:id="@+id/btnStart"
            android:text="开始"></Button>
        <Button
            android:layout_width="150dp"
            android:layout_height="wrap_content"
            android:layout_marginLeft="80dp"
            android:onClick="Album_onClick"
            android:id="@+id/btnStop"
            android:text="停止"></Button>
    </LinearLayout>
    <EditText
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:text="100"
        android:textSize="150sp"
        android:id="@+id/edtNumber"
        android:background="#D3D3D3"
        android:textAlignment="center"></EditText>
</LinearLayout>

实验二

代码:

ClockActivity

public class ClockActivity extends AppCompatActivity {
   
   

    private TextView tvClock;
    public static final String CLOCK_ACTION="com.lcl.test8.Clock_Action";
    public static  int TIME=0;//倒计时的时间

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

        tvClock=(TextView)super.findViewById(R.id.tvClock);
        //注册广播
        regReceiver();

    }

    private void regReceiver(){
   
   
        IntentFilter intentFilter=new IntentFilter();
        intentFilter.addAction(CLOCK_ACTION);
        super.registerReceiver(clockReceiver, intentFilter);
    }

    //广播接受者,接受来自ClockService(计时服务)的广播,ClockService每隔一秒钟发一次广播
    private BroadcastReceiver clockReceiver=new BroadcastReceiver(){
   
   
        @Override
        public void onReceive(Context context, Intent intent) {
   
   
            changeTime();//改变TextView中的显示时间
        }
    };

    //点击Button确定 开始发送广播,开始计时
    public void StartTimeOnclick(View view){
   
   
        EditText editTime = (EditText)findViewById(R.id.inputTime);
        //获取输入EditText的时间
        String inputTime = String.valueOf(editTime.getText());
        //将获取的字符串时间用":"分割为时,分,秒
        String[] str =inputTime.split("[:]");
        int hours = Integer.valueOf(str[0]).intValue();
        int minutes = Integer.valueOf(str[1]).intValue();
        int seconds = Integer.valueOf(str[2]).intValue();
        TIME=hours*60*60*1000+minutes*60*1000+seconds*1000;
        //启动计时服务
        startService(new Intent(this,ClockService.class));
    }

    //时间展示动态变化
    private void changeTime(){
   
   
        String timeStr="";
        if(TIME==0){
   
   
            timeStr="时间到!";
        }else{
   
   
            int hour=TIME/(1000*60*60);
            int minute=TIME%(1000*60*60)/(60*1000);
            int second=(TIME%(1000*60*60))%(60*1000)/1000;
            String hourStr = String.valueOf(hour);
            String minuteStr =String.valueOf(minute);
            String secondStr = String.valueOf(second);

            if(hour<=9){
   
   
                 hourStr="0"+hour;
            }
            if(minute<=9){
   
   
                 minuteStr="0"+minute;
            }
            if (second<=9){
   
   
                 secondStr="0"+second;
            }
            timeStr= hourStr+":"+ minuteStr+ ":"+ secondStr;
        }
        tvClock.setText(timeStr);
    }
}

ClockService

public class ClockService extends Service {
   
   

    public ClockService() {
   
   
    }

    @Override
    public void onCreate() {
   
   
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
   
   
        countTime();//执行计时功能
        return super.onStartCommand(intent, flags, startId);
    }

    //实现计时功能,每隔一秒减少总时间并MainActivity发送广播
    private void countTime() {
   
   
        new Thread(new Runnable() {
   
   
            @Override
            public void run() {
   
   
                Intent intent = new Intent(ClockActivity.CLOCK_ACTION);
                while (true) {
   
   
                    try {
   
   
                        Thread.sleep(1000);
                        if (ClockActivity.TIME <= 0) {
   
   
                            sendBroadcast(intent);
                            break;
                        }
                        ClockActivity.TIME -= 1000;
                        sendBroadcast(intent);
                    } catch (InterruptedException e) {
   
   
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
   
   
        return null;
    }

}

布局文件:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

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

        <EditText
            android:layout_width="200dp"
            android:layout_height="80dp"
            android:id="@+id/inputTime"
            android:layout_marginTop="10dp"
            android:layout_marginLeft="20dp"
            android:text="输入时间"
            android:textAlignment="center"></EditText>
        <Button
            android:layout_width="150dp"
            android:layout_height="80dp"
            android:layout_marginTop="10dp"
            android:layout_marginLeft="20dp"
            android:textSize="30dp"
            android:text="确定"
            android:onClick="StartTimeOnclick"
            />
    </LinearLayout>
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="400dp">
        <TextView
            android:layout_width="380dp"
            android:layout_height="300dp"
            android:layout_centerInParent="true"
            android:background="#BDBDBD"
            android:text="计时"
            android:textSize="75dp"
            android:id="@+id/tvClock"
            android:gravity="center">
        </TextView></RelativeLayout>

</LinearLayout>

参考博文:
https://blog.csdn.net/h2503652646/article/details/86471273
https://blog.csdn.net/weixin_33913377/article/details/93254934

版权声明
本文为[osc_t4xzns0d]所创,转载请带上原文链接,感谢
https://my.oschina.net/u/4383691/blog/4708759