安卓非绑定方式的service生命周期测试


非绑定方式的service特征总结:

多次启动

startService(intent);
只会执行一次onCreate,不会产生多个实例

除非stopService,才会重新onCreate

不会执行onBind onUnbind

不会自动销毁


package com.example.administrator.myapplication;

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 {

    Button btnStart;
    Button btnStop;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btnStart=(Button)findViewById(R.id.btnStart);
        btnStop=(Button)findViewById(R.id.btnStop);
        btnStart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try{
                    Intent intent = new Intent(MainActivity.this,NoBindService.class);
                    startService(intent);
                }catch (Throwable e){
                    e.printStackTrace();
                }

              //  startActivity(intent);
            }
        });
        btnStop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this,NoBindService.class);
                stopService(intent);
            }
        });
    }
}





package com.example.administrator.myapplication;

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/12/1.
 */
public class NoBindService extends Service {

    public Service service1;
    @Override
    public void onCreate() {
        super.onCreate();
        service1=this;
        Log.i("main","onCreate");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i("main","onStartCommand");
        if(service1 == this){
            Log.i("main","相等");
        }else {
            Log.i("main","不相等");
        }
        return super.onStartCommand(intent, flags, startId);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        Log.i("main","onBind");
        return null;
    }

    @Override
    public boolean onUnbind(Intent intent) {
        Log.i("main","onUnbind");
        return super.onUnbind(intent);
    }

    @Override
    public void onDestroy() {
        Log.i("main","onDestroy");
        super.onDestroy();
    }
}

你可能感兴趣的:(安卓非绑定方式的service生命周期测试)