我最近遇到了这个问题并创建了一个解决方案。类似于隐形活动,但想法是创建一个不需要服务的“加载”活动。这是一个例子:
在 AndriodManifest.xml 中:
...
<application
... >
<activity
android:name="com.example.LoadingActivity"
android:label="@string/app_name" >
<!-- A do-nothing activity that is used as a placeholder while the service is started. -->
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.example.MyActivity"
android:label="@string/app_name" >
<!-- The real activity, started by the loading activity. -->
</activity>
<service
android:name="com.example.MyService" >
<!-- The background service, started by the loading activity. -->
</service>
</application>
...
com/example/LoadingActivity.java:
package com.example;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
public class LoadingActivity extends Activity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
super.setContentView(R.layout.activity_loading);
super.startService(new Intent(this, MyService.class)); // listed first so it will start before the activity
Intent intent = new Intent(this, MyActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); // makes it so the 'loading' activity is not kept on the back-stack
super.startActivity(intent);
}
}
MyActivity.java 和 MyService.java 文件只是标准的。您还需要一个activity_loading.xml 布局资源,可能只是一个ImageView。