Android基礎(十)服務(Service)

服務的理解

 

Android實現程序後臺運行的方案,專業術語是在進程內開啓非主線程來實現後臺運行。

 

線程的基本用法

 

Java基礎有說 java基礎(十六)多線程

 

Android多線程編程

 

前面有提到過 Android中的線程和線程池

關於異步消息機制,後面單獨說 

 

服務的基本用法

 

包括創建、啓動、停止、綁定、解綁,詳細代碼如下

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/btn_start"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="start service" />

    <Button
        android:id="@+id/btn_stop"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="stop service" />
    <Button
        android:id="@+id/btn_bind"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="bind service" />

    <Button
        android:id="@+id/btn_unbind"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="unbind service" />

    <Button
        android:id="@+id/btn_intent_service"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="intent service" />

</LinearLayout>
package www.yfg.com.servicetest;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private static final String TAG = "MainActivity";
    private Button mButtonStart;
    private Button mButtonStop;
    private Button mButtonBind;
    private Button mButtonUnBind;
    private Button mButtonIntentService;
    private MyService.downLoaderBinder mLoaderBinder;

    private ServiceConnection mServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            mLoaderBinder = (MyService.downLoaderBinder) iBinder;
            mLoaderBinder.startDownLoad();
            mLoaderBinder.getProgress();
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {

        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mButtonStart = findViewById(R.id.btn_start);
        mButtonStop = findViewById(R.id.btn_stop);
        mButtonBind = findViewById(R.id.btn_bind);
        mButtonUnBind = findViewById(R.id.btn_unbind);
        mButtonIntentService = findViewById(R.id.btn_intent_service);
        mButtonStart.setOnClickListener(this);
        mButtonStop.setOnClickListener(this);
        mButtonBind.setOnClickListener(this);
        mButtonUnBind.setOnClickListener(this);
        mButtonIntentService.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_start:
                Log.d(TAG, "onClick: " + Thread.currentThread().getId());
                Intent intentStart = new Intent(MainActivity.this, MyService.class);
                startService(intentStart);
                break;
            case R.id.btn_stop:
                Intent intentStop = new Intent(MainActivity.this, MyService.class);
                stopService(intentStop);
                break;
            case R.id.btn_bind:
                Intent intentBind = new Intent(MainActivity.this, MyService.class);
                bindService(intentBind,mServiceConnection,BIND_AUTO_CREATE);
                break;
            case R.id.btn_unbind:
                unbindService(mServiceConnection);
                break;
            case R.id.btn_intent_service:
                Log.d(TAG, "onClick: " + Thread.currentThread().getId());
                Intent intentService = new Intent(MainActivity.this, MyIntentService.class);
                startService(intentService);
                break;

        }
    }
}
package www.yfg.com.servicetest;

import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Binder;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
import android.util.Log;

public class MyService extends Service {
    private static final String TAG = "MyService";

    public MyService() {
    }

    private downLoaderBinder mLoaderBinder = new downLoaderBinder();

    class downLoaderBinder extends Binder {
        public void startDownLoad() {
            Log.d(TAG, "startDownLoad: ");
        }

        public int getProgress() {
            Log.d(TAG, "getProgress: ");
            return 0;
        }
    }

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

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(TAG, "onCreate: ");
        Intent intent = new Intent(this, MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
        Notification notification = new NotificationCompat.Builder(this)
                .setContentTitle("biaoti")
                .setContentText("neirong")
                .setWhen(System.currentTimeMillis())
                .setSmallIcon(R.mipmap.ic_launcher)
                .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
                .setContentIntent(pendingIntent)
                .build();
        startForeground(1, notification);

    }

    //啓動服務時調用
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(TAG, "onStartCommand: ");
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "onDestroy: ");
    }
}
package www.yfg.com.servicetest;

import android.app.IntentService;
import android.content.Intent;
import android.content.Context;
import android.support.annotation.Nullable;
import android.util.Log;

/**
 * An {@link IntentService} subclass for handling asynchronous task requests in
 * a service on a separate handler thread.
 * <p>
 * TODO: Customize class - update intent actions, extra parameters and static
 * helper methods.
 */
public class MyIntentService extends IntentService {
    private static final String TAG = "MyIntentService";

    public MyIntentService() {
        super("MyIntentService");
    }

    @Override
    protected void onHandleIntent(@Nullable Intent intent) {
        Log.d(TAG, "onHandleIntent: "+Thread.currentThread().getId());
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "onDestroy: ");
    }
}

服務的生命週期

 

這裏需要注意使用start和bind同時綁定服務時,銷燬服務也必須同時調用unbind和stop方法,

 

服務的高級用法

 

前臺服務和IntentService,前面的代碼有貼

 

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