D:\Program Files\Android**\app\src\main\AndroidManifest.xml:35: Error: **Activity must extend android.app.Activity [Instantiatable]
android:name=".ui.SplashActivity"
~~~~~~~~~~~~~~~~~~
Explanation for issues of type "Instantiatable":
Activities, services, broadcast receivers etc. registered in the manifest
file (or for custom views, in a layout file) must be "instantiatable" by
the system, which means that the class must be public, it must have an
empty public constructor, and if it's an inner class, it must be a static
inner class.
1 errors, 0 warnings (3 errors filtered by baseline lint-baseline.xml)
Java 方法
當(dāng)我們在 Android 應(yīng)用程序的清單文件中注冊一個活動(Activity)時,需要遵循可實例化的要求。下面是一個活動類的示例:
public class MyActivity extends AppCompatActivity {
public MyActivity() {
// This is an empty public constructor required by the system
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
}
}
上述代碼展示了一個簡單的 MyActivity 類。它繼承了 AppCompatActivity 類,并實現(xiàn)了一個空的公共構(gòu)造函數(shù),這是可實例化的要求之一。
當(dāng)我們在應(yīng)用程序的清單文件中注冊這個活動時,我們需要確保該類是公共的,例如:
<activity android:name=".MyActivity" />
如果我們忘記實現(xiàn)空的公共構(gòu)造函數(shù),或者不小心使 MyActivity 類成為一個非公共類,系統(tǒng)就無法創(chuàng)建該活動的實例,應(yīng)用程序可能會在運行時遇到錯誤或崩潰。因此,遵循可實例化的要求非常重要,以確保應(yīng)用程序在所有 Android 設(shè)備上都能正常運行。
Kotlin方法
同樣的,如果在 Kotlin 中定義的類不滿足 Instantiatable 類型要求,也會導(dǎo)致注冊組件失敗。以下是一個注冊了 Service 的 Kotlin 代碼:
<service android:name=".MyService" />
而相應(yīng)的 MyService 類定義如下:
class MyService : Service() {
// ...
}
這里同樣會遇到 Instantiatable 類型問題,因為 MyService 類沒有空的 public 構(gòu)造函數(shù)。
要解決這個問題,我們同樣需要將 MyService 聲明為 public,并添加一個空的 public 構(gòu)造函數(shù),如下所示:
class MyService : Service() {
constructor() : super() // public constructor
// ...
}
這樣就可以成功實例化 MyService,并解決 Instantiatable 類型問題了。如果你使用 Kotlin 1.1 或更高版本,還可以使用 Kotlin 的 @JvmOverloads 注解來自動生成所有可能的構(gòu)造函數(shù),例如:
class MyService @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : Service() {
// ...
}
這樣會自動生成一個空的 public 構(gòu)造函數(shù),以及一個帶參的構(gòu)造函數(shù),使得我們可以更方便地解決 Instantiatable 類型問題。
如果上面方法都處理不了的話就使用終極方法終極方法
創(chuàng)建 lint-baseline.xml文件,放在跟混淆文件的同一路徑下
<?xml version="1.0" encoding="UTF-8"?>
<issues format="6" by="lint 7.3.1" type="baseline" client="gradle" dependencies="false" name="AGP (7.3.1)" variant="fatal" version="7.3.1">
<issue
id="Instantiatable"
message="`SplashActivity` must extend android.app.Activity"
errorLine1=" android:name=".ui.SplashActivity""
errorLine2=" ~~~~~~~~~~~~~~~~~~~~">
<location
file="src/main/AndroidManifest.xml"/>
</issue>
</issues>
- 上面的 7.3.1 是gradle的插件版本 gradle plugin version
- SplashActivity 是出問題的activity
- .ui.SplashActivity 是activty在AndroidManifest.xml的路徑
最后在build.gradle中配置
android{
........
lint {
baseline = file("lint-baseline.xml")
}
}