Android 四大組件你都知道嗎

Android 四大組件你都知道嗎 

 

四大組件分別是:活動,服務,廣播,內容提供器。

先來介紹下,對其有個大概的瞭解。

1.活動就是一個用戶交互界面 2.服務,你可以理解爲後臺組件,用於服務活動的;

3.廣播,是一個可以發送一個消息,然後再去收這個消息。這個消息可以是系統發給你的,也可以是你自己發,讓其​自己接收。

4.內容提供器,實現了共享數據的組件,用於不同應用之間共享數據。

 

   接下是每個都介紹一遍吧。

  1. 活動
    簡單的說就是一個與用戶交互的一個界面,一般和佈局文件綁定,這樣才能顯示頁面內容。說到活動activity,那肯定要說說activity的生命週期。引用下我在網上找到的一張圖吧,大概的流程就是這樣的。

大概就是

①當你進入這個activity的時候,它會走onCreate() -> onStart() - > onResume().

②當你從當前頁面跳轉到另外一個頁面的時候,它會走onPause()–>onStop()

③當你從另外一個頁面返回當前頁面,它會走onRestart()–>onStart()–>onResume()

      ④最後當你退出結束這個頁面,它會走onPause()–>onStop()–>onDestroy()

 

 2.服務
      服務就是service,它是服務於活動的,爲活動處理一些耗時的操作,比如下載。

網上有很多已經講了關於service的介紹了,我這裏就簡單的說下,它怎麼用吧。

service主要有2種啓動方式。一種是startService,另外一種是bindService.

2種的區別就是startService需要在你的配置文件中去註冊這個service,最後也需要你主動去結束活動,不然它會一直運行在後臺;bindService,不需要去配置文件註冊,你只需要去綁定活動就行,它可以主動也解除綁定,然後當你綁定的活動結束後,它也會自動解除綁定。

  1. 第一種方式(startService)

需要現在配置文件註冊:

 <service android:name=".ceshi.ceshiService"/>

然後開啓服務和結束服務

        //啓動Service
        Intent intentStart = new Intent(this, ceshiService.class);
        startService(intentStart);

        //停止Service
        Intent intenStop = new Intent(this, ceshiService.class);
        stopService(intenStop);

service模塊

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;

public class ceshiService extends Service {
    @Override
    public void onCreate() {
        super.onCreate();
        //進入初始化
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        //如果多次開啓活動,每次都會走這裏
        return super.onStartCommand(intent, flags, startId);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        //服務結束
    }
}
  1. 第二種方式(bindService)
 private ceshi2Service.ceshi2Binder mBinder;

    private void bindService() {
        ServiceConnection conn = new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
                //開始
                mBinder = (ceshi2Service.ceshi2Binder) iBinder;
                mBinder.toTask();
            }

            @Override
            public void onServiceDisconnected(ComponentName componentName) {
                //結束
            }
        };
        //開始
        Intent intenBindStart = new Intent(this, ceshi2Service.class);
        bindService(intenBindStart, conn, BIND_AUTO_CREATE);
        //結束
        unbindService(conn);
    }

啓動活動需要一個ServiceConnection,用於和service之間通信。結束可以直接手動結束unbindService,也可以退出活動後自動結束。

service模塊


import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.support.annotation.Nullable;

public class ceshi2Service extends Service {

    private ceshi2Binder mBinder;

    @Override
    public void onCreate() {
        super.onCreate();
        //進入初始化
        mBinder = new ceshi2Binder();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        //如果多次開啓活動,每次都會走這裏
        return super.onStartCommand(intent, flags, startId);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        if (mBinder != null) {
            return mBinder;
        }
        return null;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        //服務結束
    }
    class ceshi2Binder extends Binder {
        public void toTask() {
           //toTask
        }
    }

}

3.廣播

這塊就是接收信息用的,可以是系統發的信息,也可以是自己發送的信息,自己接收。對這塊的詳細解釋就不寫了,也只寫下它的用法吧。

//因爲篇幅問題,這裏講解下靜態註冊和動態註冊,然後只講自己發送和自己接收這塊。

①靜態註冊

先創建接收的廣播

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

public class ceshiReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        //接收信息
        String mes = intent.getStringExtra("mess");
    }
}

先去配置文件註冊

 <receiver android:name=".ceshi.ceshiReceiver"/>

然後去發送廣播

        Intent intent = new Intent(); 
        intent.putExtra("mess", "這是發送信息");
        sendBroadcast(intent);

②動態廣播,相對於靜態廣播的常駐後臺,動態廣播需要去主動銷燬廣播

 

先去動態創建廣播接收器,再去註冊它

 private MyReceiver myReceiver;
    private void initReceiver(){
        myReceiver = new MyReceiver();
        //實例化IntentFilter對象
        IntentFilter filter = new IntentFilter();
        //這裏相當於一個標識
        filter.addAction("myFilter");
        registerReceiver(myReceiver,filter);
    }
    // 創建動態廣播接收器
    class MyReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            //接收信息
            String mes = intent.getStringExtra("mess");
        }
    }

最後是發送廣播

private void toSendReceiver() {
        Intent intent = new Intent();
        intent.setAction("myFilter");
        intent.putExtra("mess", "這是發送信息");
        sendBroadcast(intent);
    }

 

最後你還需要在結束的時候銷燬它

 @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(myReceiver);
    }
  1. 最後來講下內容提供器吧,這個是用於不同應用之間的共享數據。當然是有限制的,你只能讀取到應用開放的內容。

規則就是content://<app 包名>/<表名>

這裏講解下關於讀取內容吧,關於創建這裏就不講來,可以參考https://www.jianshu.com/p/a5de880973f3

這裏講的是關於讀取手機系統的聯繫人信息。因爲這個信息讀取也是手機系統開發的,我們才能讀取,所以讀取下面的內容,你需要先去申請權限。

關於讀取就是下面的代碼。

 //讀取聯繫人
    private void readPhoneList() {
        Cursor cursor = null;
        try {
            //查詢聯繫人
            cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                    null, null, null, null);
            while (cursor.moveToNext()) {
                //讀取聯繫人姓名
                String phoneName = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
                //讀取聯繫人手機號
                String phoneNumber = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            if (cursor != null) {
                cursor.close();
            }
        }

看了上面的代碼,你可以會很疑惑,這和上面將的content://<app 包名>/<表名>有什麼聯繫。

  //查詢聯繫人
            cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                    null, null, null, null);

這就是讀取手機信息。然後你按ctrl+左鍵,點擊下面的代碼,可以看到這個的詳細信息

ContactsContract.CommonDataKinds.Phone.CONTENT_URI。

之後你會看到

  /**
             * The content:// style URI for all data records of the
             * {@link #CONTENT_ITEM_TYPE} MIME type, combined with the
             * associated raw contact and aggregate contact data.
             */
            public static final Uri CONTENT_URI = Uri.withAppendedPath(Data.CONTENT_URI,
                    "phones");

還是有點不像之前的規則,然後再ctrl+左鍵CONTENT_URI 你會看到

   /**
         * The content:// style URI for this table, which requests a directory
         * of data rows matching the selection criteria.
         */
        public static final Uri CONTENT_URI = Uri.withAppendedPath(AUTHORITY_URI, "data");

之後再次點擊AUTHORITY_URI

    /** The authority for the contacts provider */
    public static final String AUTHORITY = "com.android.contacts";
    /** A content:// style uri to the authority for the contacts provider */
    public static final Uri AUTHORITY_URI = Uri.parse("content://" + AUTHORITY);

最後就是和之前的規則一樣了。

 

 

Ok.今天的四大組件就講到這裏。如果有什麼不懂的,或者一起探討技術的,可以加我qq:2019793673。或者加q羣:1033629708一起學習探討技術。

 

                                                             歡迎關注我的公衆號

                                            

                                                                 期待的你關注

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章