首先,對於安卓開發,目前世界上流行的是使用的是Android studio 2.0 。(hh 學著來唄 書上說用這個,,)
今後就定一個計劃 每天更新一個Android 隨筆,增強一下自控力吧!!!
(∩_∩) 相信自己可以做到!!!
第一天 Intent用法
直接上程式碼
可見intent用法大體上有三種
- 顯示呼叫 構造出intent後 傳入FirstActivity.this 作為上下文 傳入SecondAcctivity.class 作為目標活動 最後用startActivity執行這個Intent
- 隱式呼叫
- 首先 給出要被動響應的活動 在AndroidManifest.xml里加上 action 和 category(MY_CATEGORY這個是後面可以呼叫函式加上的 暫時可以不加)
- 然後即可
Intent intent = new Intent("com.example.activitytest.ACTION_START");
startActivity(intent); 進行隱式呼叫 其中 intent這種建立方法便是傳入了action的字串,表明我要啟動的活動,category 這裡是default表示為預設的category。 每個Intent可以指定一個action 但是可以指定多個category 下面可以通過這句來增加一個category。 intent.addCategory("com.example.activitytest.MY_CATEGORY");
- 注意這裡 對應一定要在要啟動的活動的 intent-filter 加入 category 宣告!!!
- 首先 給出要被動響應的活動 在AndroidManifest.xml里加上 action 和 category(MY_CATEGORY這個是後面可以呼叫函式加上的 暫時可以不加)
- 其他用法
- 開啟網頁 這裡首先 要配置<intent-filter>裡的data標籤!!! 使得ThirdActivity可以響應所有的http協議的intent
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("http://www.baidu.com"));
startActivity(intent); - 打電話 協議為tel
Intent intent = new Intent(Intent.ACTION_DIAL);
intent.setData(Uri.parse("tel:10086"));
startActivity(intent); - 傳資料
- 首先 你想把活動FirstActivity的資料傳給活動SecondActivity
- String data = "hello SecondActivity";
Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
intent.putExtra("extra_data", data);
startActivity(intent); 用的是putExtra 傳遞資料 extra_data為鍵值 後面的data為實際要傳的資料!!! - 然後在SecondActivity 先用getIntent獲得用於啟動本活動的intent 在呼叫get X Extra獲取傳遞的資料 X代表 型別 有String Boolean Int等等
- 不僅僅如此 還可以傳遞資料給上一個活動哦。。。 方法是用 startActivityForResult方法來 做到對一個活動在銷燬時返回一個本活動的結果給上一個活動
Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
startActivityForResult(intent, 1); 這裡用startActivityForResult啟動SecondActivity 而不是startActivity。其中1是請求碼 只要是唯一值就可以!!!這裡在SecondActivity裡添加了活動結束後的返回資料邏輯 setResult方法是用來專門向上一個活動返回資料的,putExtra把資料存在了intent裡。 一般第一個引數有RESULT_OK 和 RESULT_CANCELED 第二個引數是帶有資料的intent 。 finish 銷燬活動。
由於返回了FirstActivity活動 故在這裡重寫這個方法來接受返回的資料。
requestCode是請求碼 resultCode是setResult時設定的處理結果 data就是傳入的帶資料的intent
- !!!這裡是通過點選按鈕結束的活動從而進行傳遞資料 如果是按下back鍵回到FirstActivity的 我們可以重寫 onBackPressed()方法來解決這個問題啦
- 開啟網頁 這裡首先 要配置<intent-filter>裡的data標籤!!! 使得ThirdActivity可以響應所有的http協議的intent
以上是小葉子自己學習中做的一些筆記哈,歡迎大家一起討論,指出不足,共同進步!!!