安卓服務的啓動、停止、綁定與解綁的簡單使用

佈局文件

<?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();
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章