1.先導入函示庫(build.gradle: Module)
dependencies {
implementation 'com.takwolf.android:foreback:0.1.1'
}
2.創建一個類別繼承Application並實現Foreback.Listener
import android.app.Activity
import android.app.Application
import android.util.Log
import com.takwolf.android.foreback.Foreback
class MyApplication : Application(), Foreback.Listener {
override fun onCreate() {
super.onCreate()
Foreback.init(this)
Foreback.registerListener(this)
}
override fun onApplicationEnterForeground(activity: Activity?) {
Toast.makeText(activity, "前台", Toast.LENGTH_SHORT).show()
}
override fun onApplicationEnterBackground(activity: Activity?) {
Toast.makeText(activity, "後台", Toast.LENGTH_SHORT).show()
}
}
3.到AndroidManifest.xml註冊 已繼承Application跟實現Foreback.Listener的類別
<application
android:name=".MyApplication"
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">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
4.效果展示