[英]App goes back to first activity if paused and relaunched from launcher icon
Basically, whenever I launch a second activity and pause the application and relaunch app by tapping on its icon in launcher, app does not resumes on second activity but goes back to first activity. 基本上,每当我启动第二个活动并通过点击启动器中的图标暂停应用程序并重新启动应用程序时,该应用程序都不会在第二个活动中恢复,而是会返回到第一个活动。 On top of that, if I pause the app(view in task manager), which app makes shows whole activity again like really fast(talking in milliseconds) and then continues to task manager.
最重要的是,如果我暂停了该应用程序(任务管理器中的视图),该应用程序将再次以非常快的速度(以毫秒为单位)显示整个活动,然后继续执行任务管理器。
Manifest file 清单文件
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme"
tools:replace="android:icon">
<activity
android:name=".Activity.MainActivity"
android:launchMode="singleTask">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".Activity.ReferenceActivity"
android:configChanges="orientation|screenSize" /> <!-- Find a better solution for orientation change -->
<meta-data
android:name="preloaded_fonts"
android:resource="@array/preloaded_fonts" />
<activity android:name=".Activity.AboutActivity"></activity>
</application>
Since you would have noticed launchMode set to "singleTask", there is a reason behind it. 由于您会注意到launchMode设置为“ singleTask”,因此背后有一个原因。 My app contains recycler view.
我的应用程序包含回收者视图。 Its data is updated from second activity.
其数据是从第二个活动更新的。 Without launchMode set to singleTask, recyclerview data is not updated so to update the data I had to relaunch whole app just to see any data change.
如果没有将launchMode设置为singleTask,则不会更新recyclerview数据,因此要更新数据,我必须重新启动整个应用程序才能看到任何数据更改。 It is a temporary workaround but I am hoping if someone would help me on this matter as well.
这是暂时的解决方法,但我希望有人也能在此问题上为我提供帮助。
About reycler view not updating, I have asked about that question countless times but never got a solution. 关于雷克莱尔的观点没有更新,我无数次询问了这个问题,但从未找到解决方案。 Yes, I have gone through probably hundreds of similar problems on stack over flow and none of them work.
是的,我可能在堆栈上遇到了数百个类似的问题,但是这些问题都不起作用。 Please bear in mind that I am beginner in Android development hence I do not have knowledge on advanced things like MvvM, RxJava or live data architecture.
请记住,我是Android开发的初学者,因此我对MvvM,RxJava或实时数据架构等高级知识不了解。
PS Just so any one gives a solution that I recall my data loader function again somewhere in onStart or on Resume, I have tried that countless times and it does not works. PS就是这样,任何人都提供了一种解决方案,我可以在onStart或Resume的某个地方再次调用我的数据加载器功能,我已经尝试了无数次,但是它不起作用。 My app is not using fragments or any other advanced stuff just basic activities.
我的应用程序不使用片段或任何其他高级内容,而只是基本活动。 Any help is appreciated!
任何帮助表示赞赏!
Second activity 第二次活动
class ReferenceActivity : AppCompatActivity() {
private var dbHandler: PediaDatabase? = null
private var note = UserNotes()
private var noteExisted: Boolean = false
private var cardAdapterPos: Int? = null
private var title: String? = null
private var text: String? = null
private var sharingMenuOpened: Boolean = false
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_reference)
val toolbarRef: Toolbar = findViewById(R.id.toolbarRefID)
setSupportActionBar(toolbarRef)
val toolbarTxtView = findViewById<TextView>(R.id.refToolbarTitleID)
supportActionBar!!.setDisplayShowTitleEnabled(false)
overridePendingTransition(R.anim.slide_in, R.anim.slide_out)
dbHandler = PediaDatabase(this)
val data = intent
if (!isNewNote) {
window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN)
if (data != null) {
noteExisted = true
this.cardAdapterPos = data.extras.getInt("cardPosition")
cardID = data.extras.getInt("cardID")
existingNote = dbHandler!!.readNote(cardID)
text = existingNote.noteText
title = existingNote.noteTitle
refTitleID.setText(existingNote.noteTitle, TextView.BufferType.EDITABLE)
refTextID.setText(existingNote.noteText, TextView.BufferType.EDITABLE)
toolbarTxtView.text = "Created: " + existingNote.noteDate.toString()
}
} else {
toolbarTxtView.text = "New note"
window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE)
}
}
override fun onResume() {
super.onResume()
sharingMenuOpened = false
}
override fun onPause() {
super.onPause()
if (!sharingMenuOpened)
saveNote()
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.top_menu, menu)
val addItem: MenuItem = menu!!.findItem(R.id.add_note_menu)
val delItem: MenuItem = menu.findItem(R.id.delete_note_menu)
val shareButton: MenuItem = menu.findItem(R.id.shareID)
addItem.isVisible = false
delItem.isVisible = false
shareButton.isVisible = false
if (noteExisted) {
delItem.isVisible = true
shareButton.isVisible = true
}
return true
}
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
if (item!!.itemId == R.id.delete_note_menu) {
val deletionMsg = SweetAlertDialog(this, SweetAlertDialog.WARNING_TYPE)
deletionMsg.titleText = "Delete this note?"
deletionMsg.confirmText = "Yes"
deletionMsg.setCancelable(false)
deletionMsg.setConfirmClickListener(object : SweetAlertDialog.OnSweetClickListener {
override fun onClick(sweetAlertDialog: SweetAlertDialog?) {
dbHandler!!.deleteNote(cardID)
deletionMsg.dismissWithAnimation()
val successMsg = SweetAlertDialog(this@ReferenceActivity, SweetAlertDialog.SUCCESS_TYPE)
successMsg.setCancelable(false)
successMsg.titleText = "Note deleted!"
successMsg.setConfirmClickListener(object : SweetAlertDialog.OnSweetClickListener {
override fun onClick(sweetAlertDialog: SweetAlertDialog?) {
successMsg.dismissWithAnimation()
finish()
}
}).show()
}
})
deletionMsg.setCancelButton("No", object : SweetAlertDialog.OnSweetClickListener {
override fun onClick(sweetAlertDialog: SweetAlertDialog?) {
deletionMsg.dismissWithAnimation()
}
})
deletionMsg.show()
}
if (item.itemId == R.id.shareID) {
var sharingTitle: String = title!!.trim()
var sharingText: String = text!!.trim()
sharingMenuOpened = true
val sharingIntent = Intent(android.content.Intent.ACTION_SEND)
sharingIntent.type = "text/plain"
val shareBody: String? = sharingText
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, sharingTitle)
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody)
startActivity(Intent.createChooser(sharingIntent, "Share to"))
}
return super.onOptionsItemSelected(item)
}
private fun saveNote() {
title = refTitleID.text.toString().trim()
text = refTextID.text.toString().trim()
if (existingNote.noteText == text && existingNote.noteTitle == title) {
finish()
} else {
if (noteExisted) {
if (TextUtils.isEmpty(title) && TextUtils.isEmpty(text)) {
dbHandler!!.deleteNote(cardID)
val parsedColor = Color.parseColor("#263238")
Toasty.Config.getInstance().setInfoColor(parsedColor).apply()
Toasty.info(this, "Note deleted", Toast.LENGTH_SHORT, true).show()
} else {
if (TextUtils.isEmpty(title))
title = "No title"
existingNote.noteTitle = title
existingNote.noteText = text
existingNote.noteDate = System.currentTimeMillis().toString()
dbHandler!!.updateNote(existingNote)
Toasty.success(this, "Note saved", Toast.LENGTH_SHORT, true).show()
startActivity(Intent(this, MainActivity::class.java))
finish()
}
} else {
if (TextUtils.isEmpty(title) && TextUtils.isEmpty(text)) {
finish()
} else {
if (TextUtils.isEmpty(title))
title = "No title"
note.noteTitle = title
note.noteText = text
note.noteDate = System.currentTimeMillis().toString()
dbHandler!!.createNote(note)
Toasty.success(this, "Note saved", Toast.LENGTH_SHORT, true).show()
startActivity(Intent(this, MainActivity::class.java))
finish()
}
}
}
}
} }
You can try use this in MainActivty: 您可以尝试在MainActivty中使用它:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (Intents.isActivityExpandedFromLauncherIcon(this)) {
finish()
} else {
setContentView(R.layout.activity_main)
}
}
upd: UPD:
public class Intents {
public static boolean isActivityExpandedFromLauncherIcon(@NonNull Activity activity) {
return !activity.isTaskRoot() && isActivityStartedFromLauncherIcon(activity.getIntent());
}
public static boolean isActivityStartedFromLauncherIcon(@Nullable Intent intent) {
return intent != null &&
intent.hasCategory(Intent.CATEGORY_LAUNCHER) &&
intent.getAction() != null &&
intent.getAction().equals(Intent.ACTION_MAIN);
}
} }
You are invoking finish()
in saveNote()
method, which is being called in onPause()
, hence every time your app goes into background, current activity is being finished (closed) due to invokation of finish()
in it. 您正在用
saveNote()
方法调用finish()
,该方法在onPause()
被调用,因此,每当您的应用进入后台时,由于调用了finish()
导致当前活动结束(关闭)。
Remove the calls to finish()
in saveNote()
method, and you will be resumed to your current activity instead of landing on launcher/Main Activity. 删除
saveNote()
方法中对finish()
的调用,您将恢复到当前活动,而不是登陆启动器/ Main Activity。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.