实验要求:
- 完成一个秒表,具备启停功能
- 通过绑定服务实现功能,通过Thread+handler更新界面
实验工具:
、Android studio
实验截图
理解
关于本次实验的理解:
使用绑定服务,看下面这张图的右边部分:
参照上次使用activity,使用service,new 一个service,它会自己在manifest里注册。
写好Service后,要generate一下,点击小图标(//薯条是水印哈)等待一下
MyService 写的部分也和activity类似,有onCreate,onStart等。。
在MainActivity中定义好MyService,
1.定义好ServiceConnection
public void onServiceConnected(ComponentName className, IBinder service) { //绑定服务1.用Binder传递服务接口 MyService.MyBinder binder = (MyService.MyBinder) service; mService = binder.getService(); mBound = true; }2.这个时候同时在MyService中写 ,MyBinder继承Binder服务
3.当然,我们用了绑定服务,就有onBind()(看上面流程图),在MySerice中,
public IBinder onBind(Intent intent) { // TODO: Return the communication channel to the service. return binder; //throw new UnsupportedOperationException("Not yet implemented"); }当然也有onUnBind()
public boolean onUnbind(Intent intent) { return super.onUnbind(intent); }
很好,这个时候相当于把binder这个东西定义完了,然后怎么用呢,继续往下看
当然在做Android的东西,我们都是按照它的生命周期来一步步实现的
首先要写xml文件哈
写完后
在MainActivity中
1.onCreate():
所有控件findViewById
//所有的定义都可以在外面定义好
需要的Button添加监听器,可以使用Myservice中的函数
例如:
bt_clear.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if(mBound==true){ mService.clearcount(); mService.countstop(); } } });2.onStart()
protected void onStart() { super.onStart(); Intent intent=new Intent(this,MyService.class); //绑定服务,建立连接 bindService(intent,connection, Context.BIND_AUTO_CREATE); }很清晰了吧,需要intent,和你刚刚弄的SericeConnection(它用了Binder)
这个时候又来到了MyService
在 Service中使用线程,
1.onCreate()
public void onCreate() { super.onCreate(); //2.定义线程 workThread=new Thread(null,backgroundWork); //3.启动线程 workThread.start(); }
线程怎么创建的呢?
1.实现Runnable接口
private Runnable backgroundWork =new Runnable() { @Override public void run() { //abaabaaba }}
2.定义、启动,在onCreate()中,上面
最后别忘了
onStop()
Code
<?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="wrap_content"
android:orientation="vertical"
>
<TextView
android:id="@+id/textview"
android:layout_gravity="center_horizontal"
android:text="计时器"
android:textSize="46sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:id="@+id/textview_2"
android:gravity="center"
android:textSize="54sp"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<LinearLayout
android:layout_gravity="center_horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<Button
android:id="@+id/bt_clear"
android:text="清零"
android:textSize="36sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<Button
android:id="@+id/bt_stop"
android:text="暂停"
android:textSize="36sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<Button
android:id="@+id/bt_start"
android:text="计时"
android:textSize="36sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
</LinearLayout>
package com.example.op5;
import androidx.appcompat.app.AppCompatActivity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
static TextView textView1,textView2;
Button bt_clear,bt_stop,bt_start;
MyService mService;
boolean mBound;
static int count;
static Handler handler=new Handler();
//服务建立连接
private ServiceConnection connection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName className, IBinder service) {
//绑定服务1.用Binder传递服务接口
MyService.MyBinder binder = (MyService.MyBinder) service;
mService = binder.getService();
mBound = true;
}
@Override
public void onServiceDisconnected(ComponentName arg0) {
mBound = false;
}
};
public static void UpdateGUI(int s_count)
{
count=s_count;
//将RefreshText线程加入消息队列
handler.post(RefreshText);
}
//创建线程
private static Runnable RefreshText=new Runnable() {
@Override
public void run() {
String sa,sb,sc;
int a=count%100;
if(a<10)sa="0"+a;else sa=String.valueOf(a);
int b=(count/100)%60;
if(b<10)sb="0"+b;else sb=String.valueOf(b);
int c=(count/100/60)%60;
if(c<10)sc="0"+c;else sc=String.valueOf(c);
textView2.setText(sc+":"+sb+":"+sa);
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mBound=false;
textView1=(TextView) findViewById(R.id.textview);
textView2=(TextView) findViewById(R.id.textview_2);
bt_clear=(Button) findViewById(R.id.bt_clear);
bt_stop=(Button) findViewById(R.id.bt_stop);
bt_start=(Button) findViewById(R.id.bt_start);
bt_clear.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(mBound==true){
mService.clearcount();
mService.countstop();
}
}
});
bt_start.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(mBound==true)
{
mService.countstart();
}
}
});
bt_stop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(mBound==true)
{
mService.countstop();
}
}
});
}
@Override
protected void onStart() {
super.onStart();
Intent intent=new Intent(this,MyService.class);
//绑定服务,建立连接
bindService(intent,connection, Context.BIND_AUTO_CREATE);
}
@Override
protected void onStop() {
super.onStop();
unbindService(connection);
mBound=false;
}
}
package com.example.op5;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
public class MyService extends Service {
private final IBinder binder = new MyBinder();
private Thread workThread;
private int count=0;
private boolean c_stop=true;
public MyService() {
}
public void clearcount()
{
count=0;
}
public void countstop(){
c_stop=true;
}
public void countstart(){
c_stop=false;
}
@Override
public void onCreate() {
super.onCreate();
//2.定义线程
workThread=new Thread(null,backgroundWork);
//3.启动线程
workThread.start();
}
@Override
public boolean onUnbind(Intent intent) {
return super.onUnbind(intent);
}
//绑定服务1.1写自己的MyBinder
public class MyBinder extends Binder {
MyService getService() {
return MyService.this;
}
}
//绑定服务2.回调binder
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
return binder;
//throw new UnsupportedOperationException("Not yet implemented");
}
//线程1.创建后台贤臣
private Runnable backgroundWork =new Runnable() {
@Override
public void run() {
try {
while(true)
{
if(c_stop==false)
{
count++;
}
MainActivity.UpdateGUI(count);
Thread.sleep(10);//10毫秒计数一次Z
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
}