1. 程式人生 > >Android Service的啟動終止,以及資料傳遞的簡單案例

Android Service的啟動終止,以及資料傳遞的簡單案例

生命週期方法簡單介紹

startService()

作用:啟動Service服務  手動呼叫startService()後,自動呼叫內部方法:onCreate()、onStartCommand()  如果一個service被startService多次啟動,onCreate()只會呼叫一次  onStartCommand()呼叫次數=startService()次數

stopService()

作用:關閉Service服務  手動呼叫stopService()後,自動呼叫內部方法:onDestory()  如果一個service被啟動且被繫結,如果沒有在繫結的前提下stopService()是無法停止服務的。

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <EditText
        android:id="@+id/editData"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="這是預設資訊"
        android:inputType="textPersonName"
        android:text="這是預設資訊"
        android:layout_width="match_parent" />
    <Button
        android:id="@+id/btnStartService"
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        android:text="開啟服務"
      />

    <Button
        android:id="@+id/btnStopService"
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        android:text="終止服務" />


</LinearLayout>

然後新建一個MyService服務繼承自Service,並重寫父類的onCreate()、onStartCommand()和onDestroy()方法,如下所示:

package com.example.dpl.demoservice;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;

public class MyService extends Service {
    private boolean running=false;
    private String data="這是預設資訊";

    public MyService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }


    //在MainActivity執行完startService後執行onCreate()和該方法
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        data=intent.getStringExtra("data");
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onCreate() {  //service在第一次建立時呼叫
        super.onCreate();
        running=true;
        new Thread(){    //執行後臺執行緒
            @Override
            public void run() {
                super.run();

                while (running){    //迴圈列印
                    System.out.println(data);
                    try {
                        sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }.start();
    }

    @Override
    public void onDestroy() {   //關閉服務
        super.onDestroy();
        running=false;
    }
}

MainActivity.java

package com.example.dpl.demoservice;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private EditText editData;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        editData=findViewById(R.id.editData);
        findViewById(R.id.btnStartService).setOnClickListener(this);
        findViewById(R.id.btnStopService).setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()){
            case R.id.btnStartService:
                Intent intent=new Intent(this,MyService.class);
                //傳遞引數
                intent.putExtra("data",editData.getText().toString().trim());
                startService(intent);
                break;
            case R.id.btnStopService:
                stopService(new Intent(this,MyService.class));
                break;
        }
    }
}

執行結果:

I/System.out: 這是預設資訊5
I/System.out: 這是預設資訊5
I/System.out: 這是預設資訊0
I/System.out: 這是預設資訊0
I/System.out: 這是預設資訊0
I/System.out: 這是預設資訊0
I/System.out: 這是預設資訊0