如何在 Android 中列印當前包名?


本例演示如何列印 Android 中的當前包名。

步驟 1 − 在 Android Studio 中新建一個專案,轉到 File ⇒ New Project 並填寫所有必需詳情,以建立一個新專案。

步驟 2 − 新增以下程式碼到 res/layout/activity_main.xml。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:app="http://schemas.android.com/apk/res-auto"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:gravity="center"
   android:layout_height="match_parent"
   tools:context=".MainActivity">
   <TextView
      android:id="@+id/text"
      android:textSize="30sp"
      android:layout_width="match_parent"
      android:layout_height="match_parent" />
</LinearLayout>

在上述程式碼中,我們採用了一個文字檢視來顯示當前包名。

步驟 3 − 新增以下程式碼到 src/MainActivity.java

package com.example.myapplication;

import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;

import java.security.Security;
import java.util.Locale;

public class MainActivity extends AppCompatActivity {
   TextView textView;
   @RequiresApi(api = Build.VERSION_CODES.P)
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      textView = findViewById(R.id.text);
      textView.setText("" + getPackageName());
   }
}

讓我們試著執行你的應用程式。我假設你已將自己的 Android 移動裝置與電腦連線。要從 Android Studio 執行該應用,請開啟一個專案的活動檔案,然後單擊工具欄中的 執行  圖示。選擇你的移動裝置作為選項,然後檢視將顯示預設介面的移動裝置 −

單擊此處下載專案程式碼

更新日期:26-6-2020

1,000+ 次瀏覽

開啟你的職業生涯

透過完成課程進行認證

開始
廣告
© . All rights reserved.