• Android service启动方式


    1.Context.startService()方式启动 

    ①Context.startService()方式的生命周期: 启动时,startService –> onCreate() –> onStart()停止时,stopService –> onDestroy()如果调用者直接退出而没有停止Service,则Service 会一直在后台运行 Context.startService()方法启动服务,在服务未被创建时,系统会先调用服务的onCreate()方法,接着调用onStart()方法。如果调用startService()方法前服务已经被创建,多次调用startService()方法并不会导致多次创建服务,但会导致多次调用onStart()方法。采用startService()方法启动的服务,只能调用Context.stopService()方法结束服务,服务结束时会调用onDestroy()方法附代码

    2.Context.bindService()方式启动:①Context.bindService()方式的生命周期: 绑定时,bindService -> onCreate() –> onBind()调用者退出了,即解绑定时,Srevice就会unbindService –>onUnbind() –> onDestory()Context.bindService()方式启动 Service的方法:绑定Service需要三个参数:bindService(intent, conn, Service.BIND_AUTO_CREATE);第一个:Intent对象第二个:ServiceConnection对象,创建该对象要实现它的onServiceConnected()和 onServiceDisconnected()来判断连接成功或者是断开连接第三个:如何创建Service,一般指定绑定的时候自动创建附代码

    package com.dada.test;
    
    import android.app.Activity;
    import android.content.ComponentName;
    import android.content.Context;
    import android.content.Intent;
    import android.content.ServiceConnection;
    import android.os.Bundle;
    import android.os.IBinder;
    import android.util.Log;
    import android.view.View;
    import android.widget.Button;
    
    import com.dada.test.BindService.MyBinder;
    
    public class TestActivity extends Activity {
        
        private boolean flag;
        private static final String TAG = "TestActivity";
        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            
            super.onCreate(savedInstanceState); 
            setContentView(R.layout.main); 
     
            Button btnStart = (Button) findViewById(R.id.btnStart); 
     
            Button btnStop = (Button) findViewById(R.id.btnStop); 
     
            
            btnStart.setOnClickListener(new View.OnClickListener() { 
                @Override 
                public void onClick(View v) { 
                    //启动service 方式2
                    bindService();
                } 
            }); 
            
            btnStop.setOnClickListener(new View.OnClickListener() { 
                 
                @Override 
                public void onClick(View v) { 
     //停止service 方式2
                    unBindService();
                } 
            }); 
        }
        
        //启动service 方式2
        //
        private void bindService(){
            Intent intent = new Intent(TestActivity.this,BindService.class);
            Log.i(TAG, "bindService()");
            bindService(intent, conn, Context.BIND_AUTO_CREATE);
        }
        
        private void unBindService(){
            Log.i(TAG, "unBindService() start....");
            if(flag == true){
                Log.i(TAG, "unBindService() flag");
                unbindService(conn);
                flag = false;
            }
        }
        
    private ServiceConnection conn = new ServiceConnection() {
            
            @Override
            public void onServiceDisconnected(ComponentName name) {
                // TODO Auto-generated method stub
                Log.i(TAG, "onServiceDisconnected()");
            }
            
            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                // TODO Auto-generated method stub
                Log.i(TAG, "onServiceConnected()");
                MyBinder binder = (MyBinder)service;
                BindService bindService = binder.getService1();
                bindService.MyMethod();
                flag = true;
            }
        };
    }
    package com.dada.test;
    
    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";
        private MyBinder myBinder = new MyBinder();
        public void MyMethod(){
            Log.i(TAG, "BindService-->MyMethod()");
        }
        
        @Override
        public IBinder onBind(Intent intent) {
            Log.i(TAG, "BindService-->onBind()");
            return myBinder;
        }
        
        public class MyBinder extends Binder{
            
            public BindService getService1(){
                return BindService.this;
            }
        }
        
      
    
        @Override
        public void onCreate() {
            Log.i(TAG, "BindService-->onCreate()");
            super.onCreate();
        }
    
        @Override
        public void onStart(Intent intent, int startId) {
            Log.i(TAG, "BindService-->onStart()");
            super.onStart(intent, startId);
        }
    
        @Override
        public void onDestroy() {
            Log.i(TAG, "BindService-->onDestroy()");
            super.onDestroy();
        }
    
        @Override
        public boolean onUnbind(Intent intent) {
            Log.i(TAG, "BindService-->onUnbind()");
            return super.onUnbind(intent);
        }
        
    }

    只有在service因异常而断开连接的时候,onServiceDisconnected这个方法才会用到

    由于Service 的onStart()方法只有在startService()启动Service的情况下才调用,故使用onStart()的时候要注意这点。

    与 Service 通信并且让它持续运行

          如果我们想保持和 Service 的通信,又不想让 Service 随着 Activity 退出而退出呢?你可以先 startService() 然后再 bindService() 。当你不需要绑定的时候就执行 unbindService() 方法,执行这个方法只会触发 Service 的 onUnbind() 而不会把这个 Service 销毁。这样就可以既保持和 Service 的通信,也不会随着 Activity 销毁而销毁了。

    当然建议的方法是将service做成前台服务运行,我们只需要在onStartCommand里面调用 startForeground,然后再onDestroy里面调用stopForeground即可

    Intent i = new Intent();
                i.setClassName(getApplicationContext(), "com.activity.MyActivity");
    
            
            // 注意Intent的flag设置:FLAG_ACTIVITY_CLEAR_TOP:
            // 如果activity已在当前任务中运行,在它前端的activity都会被关闭,它就成了最前端的activity。FLAG_ACTIVITY_SINGLE_TOP:
            // 如果activity已经在最前端运行,则不需要再加载。设置这两个flag,就是让一个且唯一的一个activity(服务界面)运行在最前端。
            i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
                    | Intent.FLAG_ACTIVITY_SINGLE_TOP);
            PendingIntent pi = PendingIntent.getActivity(this, 0, i, 0);
            Notification myNotify = new Notification.Builder(this)
                    .setSmallIcon(R.drawable.logo)
                    .setContentTitle("我的软件")
                    .setContentText("正在运行中").setContentIntent(pi)
                    .getNotification();
            // 设置notification的flag,表明在点击通知后,通知并不会消失,也在最右图上仍在通知栏显示图标。这是确保在activity中退出后,状态栏仍有图标可提下拉、点击,再次进入activity。
            myNotify.flags |= Notification.FLAG_NO_CLEAR;
    
            // 步骤 2:startForeground( int,
            // Notification)将服务设置为foreground状态,使系统知道该服务是用户关注,低内存情况下不会killed,并提供通知向用户表明处于foreground状态。
            startForeground(12345, myNotify);
  • 相关阅读:
    Java泛型方法
    HashMap,LinkedHashMap和TreeMap的区别
    HashSet,TreeSet和LinkedHashSet的区别
    Java中Arrays.sort()和Collections.sort()
    Java基础面试集合
    面试:字符串中的相关试题
    Hadoop相关知识整理系列之一:HBase基本架构及原理
    Ubuntu 15.10环境下安装Hive
    机器学习相关知识整理系列之三:Boosting算法原理,GBDT&XGBoost
    机器学习相关知识整理系列之二:Bagging及随机森林
  • 原文地址:https://www.cnblogs.com/chenlong-50954265/p/4980039.html
Copyright © 2020-2023  润新知