XML布局构思
- 总体是垂直线性布局,放4个按钮即可
MyService.java
- 继承Service类实现自动计数的功能
public class Myservice extends Service {
int count;
boolean flag;
public class MyBind extends Binder{
public int getconut(){
return count;
}
public void setcount(int args){
count=args;
}
}
MyBind myBind = new MyBind();
@Nullable
@Override
public IBinder onBind(Intent intent) {
return myBind; //传回count值
}
@Override
public void onCreate() {
super.onCreate();
flag=true;
new Thread() {
@Override
public void run() {
super.run();
while (flag) {
try {
Thread.sleep(1000);
//1000毫秒就是1秒,秒以下是1000进制
} catch (InterruptedException e) {
e.printStackTrace();
}
count++;
}
}
}.start();
}
//停止service
@Override
public void onDestroy() {
super.onDestroy();
flag=false;
}
}
Mainactivity.java
public class MainActivity extends AppCompatActivity {
private Intent intent;
private ServiceConnection serviceConnection;
private Myservice.MyBind bind;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
intent = new Intent(MainActivity.this,Myservice.class);
serviceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder iBinder) {
bind = (Myservice.MyBind) iBinder; //从Service返回回来的MyBind对象
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
};
}
public void btn1(View view) {
bindService(intent, serviceConnection, BIND_AUTO_CREATE); //绑定service加启动
Toast.makeText(getApplicationContext(),"绑定成功",Toast.LENGTH_SHORT).show();
}
public void btn2(View view) {
Toast.makeText(getApplicationContext(),"解绑成功!",Toast.LENGTH_SHORT).show();
unbindService(serviceConnection); //解绑
/* try { } catch (Exception ignore) {
Toast.makeText(getApplicationContext(),"当前没有绑定,无需解绑",Toast.LENGTH_SHORT).show();
}*/
}
public void btn3(View view) {
try {
Toast.makeText(getApplicationContext(),"当前的值是:"+bind.getconut()+"",Toast.LENGTH_SHORT).show();
}catch (Exception ignore){
Toast.makeText(getApplicationContext(),"当前没有绑定,无法取值!",Toast.LENGTH_SHORT).show();
}
}
public void btn4(View view) {
try {
bind.setcount(0); //清零
Toast.makeText(getApplicationContext(),"已经清零",Toast.LENGTH_SHORT).show();
}catch (Exception ignore){
Toast.makeText(getApplicationContext(),"当前没有绑定,无需清零!",Toast.LENGTH_SHORT).show();
}
}
}
实现效果图