布局文件
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<LinearLayout
android:orientation="vertical"
android:gravity="center"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:id="@+id/randomNum"
android:text="生成随机数"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="@+id/stopService"
android:text="停止服务"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/randomText"
android:text="随机数"
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<!--加法-->
<LinearLayout
android:orientation="horizontal"
android:gravity="center"
android:layout_gravity="center"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="@+id/add1"
android:text="被加数"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:text="+"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/add2"
android:text="加数"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:text="="
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/result"
android:text="运算结果"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
<Button
android:id="@+id/addBtn"
android:text="相加"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="@+id/bindService"
android:text="绑定服务"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="@+id/unbindService"
android:text="取消绑定服务"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
</android.support.constraint.ConstraintLayout>
活动
package com.zhang.app;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private static final String TAG = "MyBindService";
private Button startService,stopService,addBtn,bindBtn,ubindBtn;
private TextView add1,add2,computRet;
private Intent serviceIntent,addServiceIntent;
private static TextView ret;
private static double num;
// 获取服务对象
private addService addops;
private ServiceConnection connection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
addops = ((addService.MyBinder) service).getService();
Log.i(TAG, "onServiceConnected: ");
}
@Override
public void onServiceDisconnected(ComponentName name) {
// addservice = null;
}
};
private static Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
Log.i("mess", "handleMessage: "+msg);
ret.setText("随机数:"+num);
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}
private void initView(){
startService = findViewById(R.id.randomNum);
stopService = findViewById(R.id.stopService);
ret = findViewById(R.id.randomText);
addBtn = findViewById(R.id.addBtn);
add1 = findViewById(R.id.add1);
add2 = findViewById(R.id.add2);
computRet = findViewById(R.id.result);
bindBtn = findViewById(R.id.bindService);
ubindBtn = findViewById(R.id.unbindService);
startService.setOnClickListener(this);
stopService.setOnClickListener(this);
bindBtn.setOnClickListener(this);
ubindBtn.setOnClickListener(this);
addBtn.setOnClickListener(this);
serviceIntent = new Intent(this,randomService.class);
addServiceIntent = new Intent(this,addService.class);
}
@Override
public void onClick(View v) {
Log.i("click", "onClick: ");
if(v.getId() == R.id.randomNum){
startService(serviceIntent);
}else if(v.getId() == R.id.stopService){
stopService(serviceIntent);
}else if(v.getId() == R.id.bindService){
bindService(addServiceIntent,connection,BIND_AUTO_CREATE);
}else if(v.getId() == R.id.unbindService){
unbindService(connection);
}else if (v.getId() == R.id.addBtn){
int addnum1,addnum2;
addnum1 = getRandom();
addnum2 = getRandom();
add1.setText(""+addnum1);
add2.setText(""+addnum2);
Log.i("ret", "onClick: "+addops.addNum(addnum1,addnum2));
computRet.setText(""+addops.addNum(addnum1,addnum2));
}
}
public int getRandom(){
int number = (int) (Math.random()*100);
return number;
}
public static void setNumber(double number){
num = number;
Log.i("output", "setNumber: "+number);
handler.sendEmptyMessage(0x123);
}
}
绑定与解绑
package com.zhang.app;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.os.IInterface;
import android.os.Parcel;
import android.os.RemoteException;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import java.io.FileDescriptor;
public class addService extends Service {
private static final String TAG = "MyBindService";
private final IBinder binder = new MyBinder();
public class MyBinder extends Binder {
public addService getService(){
return addService.this;
}
}
public addService() {
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
Log.i("add1", "onBind: ");
// throw new UnsupportedOperationException("Not yet implemented");
return binder;
}
@Override
public void onRebind(Intent intent) {
super.onRebind(intent);
}
@Override
public boolean onUnbind(Intent intent) {
Log.i("add2", "onUnbind: ");
return super.onUnbind(intent);
}
@Override
public void onCreate() {
super.onCreate();
Log.i("add3", "onCreate: ");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i("add4", "onStartCommand: ");
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
super.onDestroy();
Log.i("add4", "onDestroy: ");
}
// 定义方法
public int addNum(int val1,int val2){
Log.i(TAG, "addNum: "+(val1 + val2));
return val1 + val2;
}
}
启动与停止
package com.zhang.app;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;
public class randomService extends Service {
private Thread thread;
private double number;
public randomService() {
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public void onCreate() {
super.onCreate();
Log.i("create", "onCreate: ");
thread = new Thread(){
@Override
public void run() {
super.run();
Looper.prepare();
try {
while (true){
number = Math.random();
// Toast.makeText(getApplicationContext(),"随机数:"+number,Toast.LENGTH_LONG).show();
MainActivity.setNumber(number);//调用另一个类中的静态方法
Thread.sleep(1000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
Looper.loop();
}
};
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if(!thread.isAlive())
thread.start();
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
super.onDestroy();
Log.i("destory", "onDestroy: ");
if(thread.isAlive())
thread.interrupt();
}
}