当前位置:网站首页>Android Development - service application, timer implementation (thread + service)

Android Development - service application, timer implementation (thread + service)

2020-11-09 10:56:00 osc_t4xzns0d

Experimental topics

  1. Implement a countdown clock , Create sub line to realize timing function , Use asynchronous message mechanism to display timing results on the interface , Pictured , Enter the number in the text box ( Use Number The text box ), After you click the start button , The number in the text box below is minus... Per second 1, Click stop to stop the countdown
  2. establish ClockActivity, You can enter a time , Create another ClockService It's used for timing , When it's time , In the Activity To give notice of ( Underneath TextView It shows that “ Time out ”).
    Be careful : This is where Service operation Activity

Experiment 1

Code :

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){
   
   
                                    // One second apart 
                                    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){
   
   
                    // stop it 
                    iswork=false;
                }
            }
        });
    }

}
Layout file :
<?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=" Start "></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=" stop it "></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>

Experiment two

Code :

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;// The countdown time 

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

        tvClock=(TextView)super.findViewById(R.id.tvClock);
        // Registration of radio 
        regReceiver();

    }

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

    // Radio receivers , from ClockService( Time service ) Broadcast of ,ClockService Broadcast every second 
    private BroadcastReceiver clockReceiver=new BroadcastReceiver(){
   
   
        @Override
        public void onReceive(Context context, Intent intent) {
   
   
            changeTime();// change TextView Show time in 
        }
    };

    // Click on Button determine   Start sending the broadcast , Start timing 
    public void StartTimeOnclick(View view){
   
   
        EditText editTime = (EditText)findViewById(R.id.inputTime);
        // Get input EditText Time for 
        String inputTime = String.valueOf(editTime.getText());
        // Will get the string time with ":" Divided into , branch , second 
        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;
        // Start the timer service 
        startService(new Intent(this,ClockService.class));
    }

    // Time shows dynamic change 
    private void changeTime(){
   
   
        String timeStr="";
        if(TIME==0){
   
   
            timeStr=" Time out !";
        }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();// Perform timing function 
        return super.onStartCommand(intent, flags, startId);
    }

    // Realize timing function , Reduce the total time every second and MainActivity Send a broadcast 
    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;
    }

}

Layout file :
<?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=" Input time "
            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=" determine "
            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=" timing "
            android:textSize="75dp"
            android:id="@+id/tvClock"
            android:gravity="center">
        </TextView></RelativeLayout>

</LinearLayout>

Refer to the post :
https://blog.csdn.net/h2503652646/article/details/86471273
https://blog.csdn.net/weixin_33913377/article/details/93254934

版权声明
本文为[osc_t4xzns0d]所创,转载请带上原文链接,感谢