Android組件——Service

Service(服務)是Android中實現程序後臺運行的解決方案,它適合用於去執行那些不需要和用戶交互而且還要求長期運行的任務。服務的運行不依賴於任何用戶界面,即使當程序被切換到後臺,或者用戶打開另一個應用程序,服務依然能夠保持正常運行。
但是服務是依賴於創建服務時所在的應用程序進程,當某個應用程序或進程被殺掉時,所有依賴於該進程的服務也會停止運行。

定義一個服務

新建一個類繼承自Service,並重寫其onBind()方法

package com.example.administrator.myserviceapplication;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;

/**
 * Created by Administrator on 2015/9/8.
 */
public class MyFirstService extends Service {
    @Override
    public void onCreate() {
        super.onCreate();
        Log.d("00000000000000000000000", "onCreate ");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d("00000000000000000000000", "onStartCommand ");
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d("00000000000000000000000", "onDestroy ");
    }
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}

然而在上邊的代碼中可以看到,還重寫了onCreate()、onStartCommand()、onDestory()方法,他們分別會在服務創建、啓動、銷燬的時候調用。另外爲了更清晰的瞭解service的生命週期,藉助打印日誌。
然後在Manifest中去進行註冊

 <service android:name=".MyFirstService"></service>

啓動和停止服務

首先在XML中定義一個含有兩個按鈕的佈局

<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:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/button_startservice"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="啓動服務"/>
    <Button
        android:id="@+id/button_stopservice"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="關閉服務"/>

</LinearLayout>

然後在MainActivity中添加兩個點擊事件

package com.example.administrator.myserviceapplication;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{
    private Button mButtonStart;
    private Button mButtonStop;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mButtonStart= (Button) findViewById(R.id.button_startservice);
        mButtonStop= (Button) findViewById(R.id.button_stopservice);
        mButtonStart.setOnClickListener(this);
        mButtonStop.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.button_startservice:
                start();
                break;
            case R.id.button_stopservice:
                stop();
                break;
            default:
                break;
        }
    }

    private void start() {
        Intent intent=new Intent(getApplicationContext(),MyFirstService.class);
        startService(intent);
    }

    private void stop() {
        Intent intent=new Intent(getApplicationContext(),MyFirstService.class);
        stopService(intent);
    }
}

再點擊事件裏,創建一個Intent對象,然後分別調用startService(intent)和stopService(intent)方法來對服務進行啓動和停止操作。

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