Android 中的 Service 三种启动方式

1.start Service    不会随着activity finish 而关闭,必须调用 stop方法

每次调用都会调用onstart方法

package com.weidingqiang.customnetroid;

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

import java.util.ArrayList;
import java.util.List;

public class StartService extends Service {

    private static final String TAG = StartService.class.getSimpleName();

    public StartService() {
        Log.d(TAG,"StartService()");
    }

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

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(TAG,"onStartCommand()");

        Bundle bundle = intent.getBundleExtra("bundle");

        int flag = bundle.getInt("Flag", 0);

        switch (flag)
        {
            case 0:
                Log.d(TAG, "onStartCommand()  --  0");

                List<SDownVO> list = (List<SDownVO>) bundle.getSerializable("start1");
                list.size();
                break;
            case 1:
                ArrayList<PDownVO> list1 =   bundle.getParcelableArrayList("start2");
                list1.size();
                Log.d(TAG,"onStartCommand()  --  1");
                break;
        }

        return super.onStartCommand(intent, flags, startId);
    }

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

    @Override
    public IBinder onBind(Intent intent) {
        Log.d(TAG,"onBind()");
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }
}
package com.weidingqiang.customnetroid;

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

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

public class StartActivity extends AppCompatActivity implements View.OnClickListener{

    private Button start,start1,start2,end;

    private Intent intent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test);

        start = (Button) this.findViewById(R.id.start);
        start1 = (Button) this.findViewById(R.id.start1);
        start2 = (Button) this.findViewById(R.id.start2);
        end = (Button) this.findViewById(R.id.end);

        start.setOnClickListener(this);
        start1.setOnClickListener(this);
        start2.setOnClickListener(this);
        end.setOnClickListener(this);

        intent = new Intent(this,StartService.class);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId())
        {
            case R.id.start:

                List<SDownVO> list = new ArrayList<SDownVO>();
                list.add(new SDownVO("www.baidu.com", "百度", false, 100));

                Bundle bundle = new Bundle();
                bundle.putInt("Flag", 0);
                bundle.putSerializable("start1", (Serializable) list);

                intent.putExtra("bundle",bundle);

                startService(intent);
                break;
            case R.id.start1:
                ArrayList<PDownVO> list1 = new ArrayList<PDownVO>();
                list1.add(new PDownVO("www.baidu.com", "百度", false, 100));

                Bundle bundle1 = new Bundle();
                bundle1.putInt("Flag", 1);
                bundle1.putParcelableArrayList("start2", list1);
                intent.putExtra("bundle",bundle1);

                startService(intent);
                break;
            case R.id.start2:
                finish();
                break;
            case R.id.end:
                stopService(intent);
                break;
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        stopService(intent);
    }

}

2Bind 方法

此方式会随着activity关闭 而关闭

package com.weidingqiang.customnetroid;

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

import java.util.List;

public class BindActivity extends AppCompatActivity implements View.OnClickListener{

    private Button start,start1,start2,end;

    private Intent intent;

    private ServiceConnection serviceConnection;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test);

        start = (Button) this.findViewById(R.id.start);
        start1 = (Button) this.findViewById(R.id.start1);
        start2 = (Button) this.findViewById(R.id.start2);
        end = (Button) this.findViewById(R.id.end);

        start.setOnClickListener(this);
        start1.setOnClickListener(this);
        start2.setOnClickListener(this);
        end.setOnClickListener(this);

        intent = new Intent(this,BindService.class);

        serviceConnection = new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {

            }

            @Override
            public void onServiceDisconnected(ComponentName name) {

            }
        };
    }

    @Override
    public void onClick(View v) {
        switch (v.getId())
        {
            case R.id.start:
                bindService(intent, serviceConnection,Context.BIND_AUTO_CREATE);
                break;
            case R.id.start1:
                Intent intent2 = new Intent(this,StartBindActivity.class);
                startActivity(intent2);
                finish();
                break;
            case R.id.start2:
                finish();
                break;
            case R.id.end:

                break;
        }
    }

    @Override
    protected void onStop() {

        super.onStop();
    }

    @Override
    protected void onDestroy() {
        if(isServiceRunning(this,"BindService"))
        {
            unbindService(serviceConnection);
        }

        super.onDestroy();
    }

    /**
     * 用来判断服务是否运行.
     * @param mContext
     * @param className 判断的服务名字
     * @return true 在运行 false 不在运行
     */
    public static boolean isServiceRunning(Context mContext,String className) {
        boolean isRunning = false;
        ActivityManager activityManager = (ActivityManager)
                mContext.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningServiceInfo> serviceList
                = activityManager.getRunningServices(30);
        if (!(serviceList.size()>0)) {
            return false;
        }
        for (int i=0; i<serviceList.size(); i++) {
            if (serviceList.get(i).service.getClassName().equals(className) == true) {
                isRunning = true;
                break;
            }
        }
        return isRunning;
    }
}
package com.weidingqiang.customnetroid;

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

public class BindService extends Service {

    private static final String TAG = BindService.class.getSimpleName();

    /**
     * 在 BindService 中我们直接继承 Binder 而不是 IBinder,因为 Binder 实现了 IBinder 接口,这样我们可以少做很多工作。
     */
    public class SimpleBinder extends Binder{
        /**
         * 获取 Service 实例
         * @return
         */
        public BindService getService(){
            return BindService.this;
        }

        public int add(int a, int b){
            return a + b;
        }
    }

    public SimpleBinder sBinder;

    public BindService() {
    }

    @Override
    public void onCreate() {
        super.onCreate();

        Log.d(TAG,"onCreate()");

        // 创建 SimpleBinder
        sBinder = new SimpleBinder();
    }

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

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

    @Override
    public IBinder onBind(Intent intent) {
        // 返回 SimpleBinder 对象
        return sBinder;
    }

}

3.start and bind

package com.weidingqiang.customnetroid;

import android.content.ComponentName;
import android.content.Context;
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;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

public class StartBindActivity extends AppCompatActivity implements View.OnClickListener{

    private static final String TAG = StartBindActivity.class.getSimpleName();

    private Button start,start1,start2,end;

    private Intent intent;

    private ServiceConnection serviceConnection;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test);

        start = (Button) this.findViewById(R.id.start);
        start1 = (Button) this.findViewById(R.id.start1);
        start2 = (Button) this.findViewById(R.id.start2);
        end = (Button) this.findViewById(R.id.end);

        start.setOnClickListener(this);
        start1.setOnClickListener(this);
        start2.setOnClickListener(this);
        end.setOnClickListener(this);

        intent = new Intent(this,StartBindService.class);

        serviceConnection = new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                StartBindService.SimpleBinder sBinder = (StartBindService.SimpleBinder)service;
                Log.v(TAG, "3 + 5 = " + sBinder.add(3, 5));
                Log.v(TAG, sBinder.getService().toString());
            }

            @Override
            public void onServiceDisconnected(ComponentName name) {

            }
        };
    }

    @Override
    public void onClick(View v) {
        switch (v.getId())
        {
            case R.id.start:
                startService(intent);
                bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
                break;
            case R.id.start1:
                startService(intent);
                break;
            case R.id.start2:
                Intent intent2 = new Intent(this,BindActivity.class);
                startActivity(intent2);
                finish();
                break;
            case R.id.end:
                stopService(intent);
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbindService(serviceConnection);
    }
}
package com.weidingqiang.customnetroid;

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

import java.util.ArrayList;
import java.util.List;

public class StartBindService extends Service {
    private static final String TAG = StartBindService.class.getSimpleName();

    /**
     * 在 BindService 中我们直接继承 Binder 而不是 IBinder,因为 Binder 实现了 IBinder 接口,这样我们可以少做很多工作。
     */
    public class SimpleBinder extends Binder {
        /**
         * 获取 Service 实例
         * @return
         */
        public StartBindService getService(){
            return StartBindService.this;
        }

        public int add(int a, int b){
            return a + b;
        }
    }

    public SimpleBinder sBinder;

    public StartBindService() {
    }

    @Override
    public void onCreate() {
        super.onCreate();

        Log.d(TAG, "onCreate()");

        // 创建 SimpleBinder
        sBinder = new SimpleBinder();
    }

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

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

    @Override
    public IBinder onBind(Intent intent) {
        // 返回 SimpleBinder 对象
        return sBinder;
    }
}

  

时间: 2024-08-26 23:56:36

Android 中的 Service 三种启动方式的相关文章

Android中Activity的四种启动方式

谈到Activity的启动方式必须要说的是数据结构中的栈.栈是一种只能从一端进入存储数据的线性表,它以先进后出的原则存储数据,先进入的数据压入栈底,后进入的数据在栈顶.需要读取数据的时候就需要从顶部开始读取数据,栈具有记忆功能,对栈的操作不需要指针的约束.在Android中Activity的显示其实就是一个入栈和出栈的过程.当打开一个Activity的时候Activity入栈,当关闭一个Activity的时候Activity出栈,用户操作的Activity位于栈顶,一般情况下,一个应用程序对应一

Android中常用的三种存储方法浅析

Android中常用的三种存储方法浅析 Android中数据存储有5种方式: [1]使用SharedPreferences存储数据 [2]文件存储数据 [3]SQLite数据库存储数据 [4]使用ContentProvider存储数据 [5]网络存储数据 在这里我只总结了三种我用到过的或即将可能用到的三种存储方法. 一.使用SharedPreferences存储数据 SharedPreferences是Android平台上一个轻量级的存储类,主要是保存一些常用的配置信息比如窗口状态,它的本质是基

SpringBoot三种启动方式

SpringBoot第一种启动方式 import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.

Android -- service两种启动方式startService与bindService

继上一篇文章,Android – Service的使用,我们来继续看看Service的两种启动方式 第一种startService . 运行代码,得知以下几点结论: 我们了解它的启动周期为onCreate->onStartCommand,如图 当退出应用后,后台的Service进程仍然存在,未被销毁 当点击多次startService时,如图我点击了3次,你会发现onCreate方法只创建了一次. stopService,如图 第二种bindService 运行代码得知以下结论: 点击bindS

Service 两种启动方式

Service的生命周期Service的生命周期方法比Activity少一些,只有onCreate,onStart,onDestroy 我们有两种方式启动一个Service,他们对Service生命周期的影响是不一样的. 1通过startService Service会经历onCreate->onStart stopService的时候直接onDestroy 如果是调用者(TestServiceHolder)自己直接退出而没有调用stopService的 话,Service会一直在后台运行. 下

Android中BroadcastReceiver的两种注册方式(静态和动态)详解

今天我们一起来探讨下安卓中BroadcastReceiver组件以及详细分析下它的两种注册方式. BroadcastReceiver也就是"广播接收者"的意思,顾名思义,它就是用来接收来自系统和应用中的广播.在Android系统中,广播体现在方方面面,例如当开机完成后系统会产生一条广播,接收到这条广播就能实现开机启动服务的功能:当网络状态改变时系统会产生一条广播,接收到这条广播就能及时地做出提示和保存数据等操作:当电池电量改变时,系统会产生一条广播,接收到这条广播就能在电量低时告知用户

Android自定义View的三种实现方式

在毕设项目中多处用到自定义控件,一直打算总结一下自定义控件的实现方式,今天就来总结一下吧.在此之前学习了郭霖大神博客上面关于自定义View的几篇博文,感觉受益良多,本文中就参考了其中的一些内容. 总结来说,自定义控件的实现有三种方式,分别是:组合控件.自绘控件和继承控件.下面将分别对这三种方式进行介绍. (一)组合控件 组合控件,顾名思义就是将一些小的控件组合起来形成一个新的控件,这些小的控件多是系统自带的控件.比如很多应用中普遍使用的标题栏控件,其实用的就是组合控件,那么下面将通过实现一个简单

Android自定义布局的三种实现方式

在毕设项目中多处用到自定义布局,一直打算总结一下自定义布局的实现方式,今天就来总结一下吧.在此之前学习了郭霖大神博客上面关于自定义View的几篇博文,感觉受益良多,本文中就参考了其中的一些内容. 总结来说,自定义布局的实现有三种方式,分别是:组合控件.自绘控件和继承控件.下面将分别对这三种方式进行介绍. (一)组合控件 组合控件,顾名思义就是将一些小的控件组合起来形成一个新的控件,这些小的控件多是系统自带的控件.比如很多应用中普遍使用的标题栏控件,其实用的就是组合控件,那么下面将通过实现一个简单

Redis的三种启动方式

Part I. 直接启动 下载 官网下载 安装 tar zxvf redis-2.8.9.tar.gz cd redis-2.8.9 #直接make 编译 make #可使用root用户执行`make install`,将可执行文件拷贝到/usr/local/bin目录下.这样就可以直接敲名字运行程序了. make install 启动 #加上`&`号使redis以后台程序方式运行 ./redis-server & 检测 #检测后台进程是否存在 ps -ef |grep redis #检测