Android获取应用程序名称(ApplicationName)示例

时间:2021-09-16 08:36:41

MainActivity如下:

复制代码 代码如下:


package cn.testapplicationname;
import android.os.Bundle;
import android.widget.TextView;
import android.app.Activity;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
/**
* Demo描述:
* 获取应用程序名称(ApplicationName)
*/
public class MainActivity extends Activity {
private TextView mTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
init();
}
private void init() {
mTextView = (TextView) findViewById(R.id.textView);
String applicationName = getApplicationName();
mTextView.setText("该应用名字:"+applicationName);
}
public String getApplicationName() {
PackageManager packageManager = null;
ApplicationInfo applicationInfo = null;
try {
packageManager = getApplicationContext().getPackageManager();
applicationInfo = packageManager.getApplicationInfo(getPackageName(), 0);
} catch (PackageManager.NameNotFoundException e) {
applicationInfo = null;
}
String applicationName =
(String) packageManager.getApplicationLabel(applicationInfo);
return applicationName;
}
}


main.xml如下:

复制代码 代码如下:


<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world"
android:layout_centerInParent="true"
/>
</RelativeLayout>