安卓開發之開啟服務的兩種方式


package com.lidaochen.test001;

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;

public class MainActivity extends AppCompatActivity {
    private MyConn conn;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    // 當 Activity 銷毀的時候 要解綁服務
    @Override
    protected void onDestroy() {
        // unbindService(conn);
        super.onDestroy();
    }

    // 點擊按鈕通過startService開啟服務
    public void click1(View v)
    {
        Intent intent = new Intent(this, DemoService.class);
        startService(intent);
    }
    // 點擊按鈕通過stopService關閉服務
    public void click2(View v)
    {
        Intent intent = new Intent(this, DemoService.class);
        stopService(intent);
    }
    // 點擊按鈕通過bindService綁定服務
    public void click3(View v)
    {
        Intent intent = new Intent(this, DemoService.class);
        // 連接到DemoService 這個服務
        conn = new MyConn();
        bindService(intent, conn, BIND_AUTO_CREATE);
    }
    // 點擊按鈕手動解綁服務
    public void click4(View v)
    {
        unbindService(conn);
    }

    // 定義一個類用來監視服務的狀態
    private class MyConn implements ServiceConnection
    {
        // 當服務連接成功時調用
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.e("service", "onServiceConnected!");
        }

        // 失去連接時調用
        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.e("service", "onServiceDisconnected!");
        }
    }
}
package com.lidaochen.test001;

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

public class DemoService extends Service {
    public DemoService() {
    }

    // 當服務第一次創建的時候調用
    @Override
    public void onCreate() {
        Log.e("service", "onCreate!");
        super.onCreate();
    }

    // 每次調用startService都會執行下面的方法
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.e("service", "onStartCommand!");
        return super.onStartCommand(intent, flags, startId);
    }

    // 當服務銷毀的時候調用
    @Override
    public void onDestroy() {
        Log.e("service", "onDestroy!");
        super.onDestroy();
    }

    // 調用 bindService 會調用下面的這個方法
    @Override
    public IBinder onBind(Intent intent) {
        Log.e("service", "onBind!");
        return null;
    }

}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM