我尝试从后台以编程方式恢复Android Activity,但是当我按下主页按钮时,活动会在五秒后再次启动活动。与后退按钮和最近的应用程序按钮配合良好。
为什么它会延迟五秒重启?
API级别为19,Android版本为4.4.2(KitKat)
这是代码:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.test.drawtoptest">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity"
android:launchMode="singleTop">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".Main2Activity"
android:label="@string/app_name"
android:parentActivityName=".Main2Activity"
>
</activity>
</application>
</manifest>
MainActivity.class
public class MainActivity extends AppCompatActivity {
MyTimerTask myTimerTask;
Timer timer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.button);
Button button1 = (Button) findViewById(R.id.button3);
}
public void test(){
Intent myIntent = new Intent(getBaseContext(), MainActivity.class);
myIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_SINGLE_TOP|Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(myIntent);
}
class MyTimerTask extends TimerTask {
@Override
public void run() {
test();
}
}
@Override
protected void onPause(){
if (timer == null) {
myTimerTask = new MyTimerTask();
timer = new Timer();
timer.schedule(myTimerTask, 50, 50);
}
super.onPause();
}
}