Android笔记之四大组件

1.Activity的生命周期状态(https://blog.csdn.net/ttandroid/article/details/80926753)

image.png

(1).ActivityA第一次启动,调用onCreate,onStart,onResume

(2).ActivityA启动到ActivityB的时候,A调用onPause,然后B调用onCreate, onStart, onResume,最后A在调用onStop(注意:如果A是透明的主题,A最后不会调用onStop)

(3).再次回到A时,B--->onPause,onStop,onDestory 然后A--->onRestart,onStart,onResume

(4).按Home键时,当前ActivityA--->onPause,onStop,长按home键再次回到 ActivityA时,onRestart,onStart,onResume

2.Fragment的生命周期状态(https://www.jianshu.com/p/c8f34229b6dc)

image.png

Fragment1切换到Fragment2时生命周期的变化

(1).通过add ,hide ,show 方式来切换Fragment
add-->fragemnt1周期变化-->onAttach --->onCreate-->onCreateView-->onActivityCreated-->onStart-->onResume
fragment1切换到fragment2--->fragment1周期不变化,会回调onHiddenChanged()方法
fragment2周期变化-->onAttach-->onCreate-->onCreateView-->onActivityCreated-->onStart-->onResume
fragment2再次回到fragment1时,不走任何周期性的方法但是会回调二者的onHiddenChanged()方法。

(2).通过replace的方法进行切换时:
repleace-->fragemnt1周期变化-->onAttach --->onCreate-->onCreateView-->onActivityCreated-->onStart-->onResume
fragment1切换到fragment2--->fragment1-->onPause-->onStop-->onDestoryView-->onDestory-->onDetach,fragment2-->onAttach-->onCreate-->onCreateView-->onActivityCreated-->onStart-->onResume

注意:通过repleace方法进行替换时,fragment都要重新new ,fragment都是进行了销毁,重建的过程,相当于走了一整套的生命周期。

(3).使用ViewPager进行切换时:
当使用ViewPager与Fragment进行切换时,fragment会进行预加载操作,所有的fragment都会提前初始化--预加载
加载fragment1-->onAttach-->onCreate-->onCreateView-->onActivityCreated-->onStart-->onResume同时预加载fragment2-->onAttach-->onCreate-->onCreateView-->onActivityCreated-->onStart-->onResume

当Fragment2切换到fragment1的时候,Fragment1,Fragment2不走任何生命周期方法,但是会回调

setUserVisiableHint()方法

3.Service的生命周期和二种启动方式(https://github.com/Asmewill/Genericity)

image.png
public class SimpleService extends Service {
    public class LocalBinder extends Binder {
       public  SimpleService getService(){
            return  SimpleService.this;
        }
    }
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        System.out.println("onBind invoke");
        return new LocalBinder();
    }

    @Override
    public boolean onUnbind(Intent intent) {
        System.out.println("onUnbind invoke");
        return super.onUnbind(intent);
    }

    @Override
    public void onCreate() {
        System.out.println("onCreate invoke");
        super.onCreate();
    }
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        System.out.println("onStartCommand invoke");
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        System.out.println("onDestroy invoke");
        super.onDestroy();
    }
}

 serviceConnection=new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                System.out.println("onServiceConnected");
            }

            @Override
            public void onServiceDisconnected(ComponentName name) {//取消绑定时,不会调用onServiceDisconnected
                System.out.println("onServiceDisconnected");
            }
        };
注意,一个原则是Service的onCreate的方法只会被调用一次,就是你无论多少次的startService又bindService,Service只被创建一次,当客户端取消绑定时,系统“绝对不会”调用onServiceDisconnected方法。

(1). startService(it);---->onCreate -->onStartCommand 第二次startService-->onStartCommand
(2). stopService(it);---->onDestory
(3). bindService(it,serviceConnection,BIND_AUTO_CREATE)---->onCreate-->onBind
(4). unbindService(serviceConnection)--->onUnbind-->onDestory

4.Service之AIDL跨进程

image.png


image.png

(1).在AIDL中,并非支持所有数据类型,他支持的数据类型如下所示:
基本数据类型(int、long、char、boolean、double、float、byte、short)
String和CharSequence
List:只支持ArrayList,并且里面的每个元素必须被AIDL支持
Map: 只支持HashMap, 同样的,里面的元素都必须被AIDL支持,包括key和value
Parcelable:所有实现了Parcelable接口的对象
AIDL: 所有的AIDL接口本身也可以在AIDL 文件中使用

// BookManager.aidl
package com.lypeer.ipcclient;
import com.lypeer.ipcclient.Book;

interface BookManager {

    //保证客户端与服务端是连接上的且数据传输正常
    List getBooks();

    //通过三种定位tag做对比试验,观察输出的结果
    Book addBookIn(in Book book);
    Book addBookOut(out Book book);
    Book addBookInout(inout Book book);
    String getString();
}

// Book.aidl
package com.lypeer.ipcclient;

parcelable Book;

(2).如果用到了自定义Parcelable对象,就需要创建一个同名的AIDL文件,包名要和实体类包名一致。

(3)服务端核心代码AIDLService.java

public class AIDLService extends Service {

    public final String TAG = this.getClass().getSimpleName();

    //包含Book对象的list
    private List mBooks = new ArrayList<>();

    //由AIDL文件生成的BookManager
    private final BookManager.Stub mBookManager = new BookManager.Stub() {
        @Override
        public List getBooks() throws RemoteException {
            synchronized (this) {
                Log.i(TAG, "invoking getBooks() method , now the list is : " + mBooks.toString());
                if (mBooks != null) {
                    return mBooks;
                }
                return new ArrayList<>();
            }
        }


        @Override
        public Book addBookIn(Book book) throws RemoteException {
            synchronized (this) {
                if (mBooks == null) {
                    mBooks = new ArrayList<>();
                }
                if(book == null){
                    Log.e(TAG , "Book is null in In");
                    book = new Book();
                }
                //尝试修改book的参数,主要是为了观察其到客户端的反馈
                book.setPrice(2333);
                if (!mBooks.contains(book)) {
                    mBooks.add(book);
                }
                //打印mBooks列表,观察客户端传过来的值
                Log.i(TAG, "invoking addBookIn() method , now the list is : " + mBooks.toString());
                return book;
            }
        }

        @Override
        public Book addBookOut(Book book) throws RemoteException {
            synchronized (this) {
                if (mBooks == null) {
                    mBooks = new ArrayList<>();
                }
                if(book == null){
                    Log.e(TAG , "Book is null in Out");
                    book = new Book();
                }
                book.setPrice(2333);
                if (!mBooks.contains(book)) {
                    mBooks.add(book);
                }
                Log.e(TAG, "invoking addBookOut() method , now the list is : " + mBooks.toString());
                return book;
            }
        }

        @Override
        public Book addBookInout(Book book) throws RemoteException {
            synchronized (this) {
                if (mBooks == null) {
                    mBooks = new ArrayList<>();
                }
                if(book == null){
                    Log.e(TAG , "Book is null in Inout");
                    book = new Book();
                }
                book.setPrice(2333);
                if (!mBooks.contains(book)) {
                    mBooks.add(book);
                }
                Log.i(TAG, "invoking addBookInout() method , now the list is : " + mBooks.toString());
                return book;
            }
        }

        @Override
        public String getString() throws RemoteException {
            return "aaaa";
        }
    };

    @Override
    public void onCreate() {
        Book book = new Book();
        book.setName("Android开发艺术探索");
        book.setPrice(28);
        mBooks.add(book);
        super.onCreate();
    }
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        Log.i(getClass().getSimpleName(), String.format("on bind,intent = %s", intent.toString()));
        return mBookManager;
    }
}

(4).客户端核心代码

public class AIDLActivity extends AppCompatActivity {

    //由AIDL文件生成的Java类
    private BookManager mBookManager = null;

    //标志当前与服务端连接状况的布尔值,false为未连接,true为连接中
    private boolean mBound = false;

    //包含Book对象的list
    private List mBooks;

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

    /**
     * 按钮的点击事件,点击之后调用服务端的addBookIn方法
     *
     * @param view
     */
    public void addBook(View view) {
        //如果与服务端的连接处于未连接状态,则尝试连接
        if (!mBound) {
            attemptToBindService();
            Toast.makeText(this, "当前与服务端处于未连接状态,正在尝试重连,请稍后再试", Toast.LENGTH_SHORT).show();
            return;
        }
        if (mBookManager == null) return;

        Book book = new Book();
        book.setName("APP研发录In");
        book.setPrice(30);
        try {
            mBookManager.addBookIn(book);
            Log.i(getLocalClassName(), "客户端获取BookList:"+mBookManager.getBooks().toString()+"----获取String:"+mBookManager.getString());
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    /**
     * 尝试与服务端建立连接
     */
    private void attemptToBindService() {
        Intent intent = new Intent();
        intent.setAction("com.lypeer.aidl");
        intent.setPackage("com.lypeer.ipcserver");
        bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE);
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (!mBound) {
            attemptToBindService();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (mBound) {
            unbindService(mServiceConnection);
            mBound = false;
        }
    }

    private ServiceConnection mServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.e(getLocalClassName(), "service connected");
            mBookManager = BookManager.Stub.asInterface(service);
            mBound = true;

            if (mBookManager != null) {
                try {
                    mBooks = mBookManager.getBooks();
                    Log.e(getLocalClassName(), mBooks.toString());
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.e(getLocalClassName(), "service disconnected");
            mBound = false;
        }
    };
}

5.BraodCastReceiver详解

(1).常驻型广播-->静态注册

   
            
          
   

(2).非驻型广播-->动态注册

IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(String);   //为BroadcastReceiver指定action,使之用于接收同action的广播
 registerReceiver(BroadcastReceiver,intentFilter);
注意:一般动态注册的广播,已经要在onPause或者onDestory中予以 unregisterReceiver(rhelper),否则容易造成内存泄漏。

6.ContentProvider详解

https://www.jianshu.com/p/5e13d1fec9c9

你可能感兴趣的:(Android笔记之四大组件)