![](/img/trans.png)
[英]How to Launch BraodCastReceiver in Android without any Activity?
[英]How to launch an Activity without a UI?
是否可以在沒有 UI 的情況下從主功能啟動活動? 即有沒有辦法圍繞另一個活動創建一種“包裝器”,即通過啟動主要活動,它會自動將您帶到另一個活動。
如果這是不可能的,有沒有辦法從堆棧中刪除主要活動,以便單擊后退按鈕不會將您帶到空白 UI? 這是我正在嘗試做的一個例子:
public class WrapperActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:555-1212"));
startActivity(intent);
}
}
Android 還專門為此提供了一個主題:
android:theme="@android:style/Theme.NoDisplay"
在您的清單中,當您聲明活動時,請使用主題"@android:style/Theme.Translucent.NoTitleBar"
前任:
<activity android:name="yourActivityName" android:label="@string/app_name" android:theme="@android:style/Theme.Translucent.NoTitleBar">
您需要添加 Intent 標志,
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
或者
在觸發意圖后調用“ finish();
”。
以防萬一您使用的是 Android 6.0+ 或 Target SDK 是 23+,具有主題android:theme = "@android:style/Theme.NoDisplay"
將導致崩潰,錯誤did not call finish() prior to onResume() completing
。 這實際上是 Google 開發人員在此處承認的錯誤。
因此,建議使用具有以下主題的活動作為解決方法。
android:theme = "@android:style/Theme.Translucent.NoTitleBar"
我認為這會對你有很大幫助:
<activity android:name = "MyActivity"
android:label = "@string/app_name"
android:theme = "@android:style/Theme.NoDisplay" >
使用
<activity android:name="yourActivityName" android:label="@string/app_name" android:theme="@android:style/Theme.Translucent.NoTitleBar">
Brian515 提到的效果很好。 此方法對於創建一個入口點 Activity 很有用,該入口點 Activity 決定要調用、啟動、服務等的 Activity,而無需向用戶顯示 UI。 請記住在開始意圖后使用finish()
。
我正在使用AppCompatActivity
並且此 SO 中提供的解決方案沒有解決我的問題。 這對我有用。
我在我的styles.xml
添加了以下內容。
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<!-- Customize your theme here. -->
</style>
<style name="AppTheme.NoDisplay">
<item name="android:windowBackground">@null</item>
<item name="android:windowContentOverlay">@null</item>
<item name="android:windowIsTranslucent">true</item>
<item name="android:windowAnimationStyle">@null</item>
<item name="android:windowDisablePreview">true</item>
<item name="android:windowNoDisplay">true</item>
</style>
然后,對於我想禁用顯示的任何活動,我修改如下:
<activity
android:name=".NoDisplayActivity"
android:theme="@style/AppTheme.NoDisplay">
干杯!
在您的清單中添加@android:style/Theme.Translucent.NoTitleBar"
如上面的一些答案中所述。
同時刪除setContentView(R.layout.your_activity);
來自您的 activity.java 文件的行。
我在onResume()
使用了moveTaskToBack(true)
將整個活動堆棧置於后台。
看起來類似於這里提出的問題: Removing an activity from the history stack
如果是,那么您可以使用:
FLAG_ACTIVITY_NO_HISTORY
這應該可以清除堆棧中的活動。
如果您需要從最近的應用程序中排除(長按主頁鍵),您可以使用此標志:
FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS
如果您不與 UI 交互,那么您嘗試做的事情聽起來更像是一個 android 服務。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.