Android-----Intent中通過startActivity(Intent intent )隱式啟動新的Activity


顯式Intent我已經簡單使用過了,也介紹過概念,現在來說一說隱式Intent:

隱式Intent:就是只在Intent中設置要進行的動作,可以用setAction()和setData()來填入要執行的動作和數據,然后再用startActivity()啟動合適的程序。

此外:如果手機中有多個適合的程序,還會彈出列表供用戶選擇(假如你手機有兩個瀏覽器,你打開一個連接,這是系統就會彈出兩個瀏覽器列表供你選擇)

在此舉個使用隱式Intent打開activity的快速撥號例子:

xml布局文件代碼如下:

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <LinearLayout
 3     xmlns:android="http://schemas.android.com/apk/res/android"
 4     xmlns:tools="http://schemas.android.com/tools"
 5     android:layout_width="match_parent"
 6     android:layout_height="match_parent"
 7     android:orientation="vertical"
 8     android:layout_gravity="center"
 9     tools:context="com.hs.example.exampleapplication.IntentFirst">
10 
11     <Button                  //簡單做一個Button組件
12         android:id="@+id/btn_call"
13         android:layout_width="match_parent"
14         android:layout_height="wrap_content"
15         android:background="@color/colorPrimaryLight"
16         android:textSize="18dp"
17         android:textColor="#FFFFFF"
18         android:text="打電話到10086"
19         android:onClick="onClick"/>   //點擊button是執行onClick方法,onClick方法在MainActivity中創建
20 
21 </LinearLayout>

 

我們打電話需要在AndroidManifest.xml中加入靜態申請的權限:

但是Android 6.0之后,僅僅是在配置文件中獲取權限是沒有相應權限的,還有通過動態來獲取權限,在下面的MainActivity.java中有說到

1 <uses-permission android:name="android.permission.CALL_PHONE"/>

 

MainActivity.java代碼如下:

 1 public class IntentFirst extends AppCompatActivity {
 2 
 3     private static final int REQUEST_EXTERNAL_STORAGE = 1;
 4     private static String[] PERMISSIONS_STORAGE = {"android.permission.CALL_PHONE"};//要獲取的權限,可以獲取多個
 5   //此方法用於動態獲取打電話權限
 6     public static void getCallPermissions(Activity activity) {
 7         try {
 8             //檢測是否有呼叫的權限
 9             int permission = ActivityCompat.checkSelfPermission(activity,"android.permission.CALL_PHONE");
10             if (permission != PackageManager.PERMISSION_GRANTED) {
11                 // 沒有呼叫的權限,去申請權限,會彈出對話框
12                 ActivityCompat.requestPermissions(activity, PERMISSIONS_STORAGE, REQUEST_EXTERNAL_STORAGE);
13             }
14         } catch (Exception e) {
15             e.printStackTrace();
16         }
17     }
18 
19     @Override
20     protected void onCreate(Bundle savedInstanceState) {
21         super.onCreate(savedInstanceState);
22         setContentView(R.layout.activity_intent_first);
23 
24         getCallPermissions(this);
25 
26     }
27 
28     public void onClick(View view){
29         Intent intent = new Intent();
30         intent.setAction(Intent.ACTION_VIEW);
31         intent.setData(Uri.parse("tel:10086"));
32         startActivity(intent);
33     }
34 }

運行效果如下:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM