在单独的线程中运行我的MainActivty的一部分

时间:2019-06-04 16:03:00

标签: android kotlin background-process

我正在研究在单独的线程或进程中运行onResume函数的方法,因此它不会阻止该活动的加载。

我正在寻找在MainActivity中分别运行onResume函数的方法。 onResume内是例程的集合,这些例程可在应用程序启动或恢复时从sharedPref加载回数据。但是onResume流程会延迟整个活动的加载,所以我在想的是可以从一个单独的流程运行它,以便不延迟整个活动的加载吗?

package com.taylorworld.tw1

import android.content.Context
import android.content.Context.*
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.support.design.widget.FloatingActionButton
import android.support.design.widget.Snackbar
import android.support.v4.view.GravityCompat
import android.support.v7.app.ActionBarDrawerToggle
import android.view.MenuItem
import android.support.v4.widget.DrawerLayout
import android.support.design.widget.NavigationView
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.Toolbar
import android.view.Menu
import android.view.View
import android.widget.Toast
import com.google.firebase.database.FirebaseDatabase
//import com.google.firebase.firestore.FirebaseFirestore
import kotlinx.android.synthetic.main.content_main.*
import java.sql.Types.NULL

class MainActivity : AppCompatActivity(),     NavigationView.OnNavigationItemSelectedListener {


override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    val toolbar: Toolbar = findViewById(R.id.toolbar)
    setSupportActionBar(toolbar)

    val fab: FloatingActionButton = findViewById(R.id.fab)
    fab.setOnClickListener { view ->
        val intent = Intent(this, Main2Activity::class.java)
        val sharedPref = this?.getPreferences(Context.MODE_PRIVATE)
        val mystr = sharedPref.getInt(getString(R.string.STR), 0)
        intent.putExtra("data", mystr)
        startActivity(intent)
    }
    val drawerLayout: DrawerLayout = findViewById(R.id.drawer_layout)
    val navView: NavigationView = findViewById(R.id.nav_view)
    val toggle = ActionBarDrawerToggle(
        this, drawerLayout, toolbar, R.string.navigation_drawer_open,     R.string.navigation_drawer_close
    )
    drawerLayout.addDrawerListener(toggle)
    toggle.syncState()

    navView.setNavigationItemSelectedListener(this)

    //val db = FirebaseFirestore.getInstance()
}

override fun onBackPressed() {
    val drawerLayout: DrawerLayout = findViewById(R.id.drawer_layout)
    if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
        drawerLayout.closeDrawer(GravityCompat.START)
    } else {
        super.onBackPressed()
    }
}

override fun onCreateOptionsMenu(menu: Menu): Boolean {
    // Inflate the menu; this adds items to the action bar if it is     present.
    menuInflater.inflate(R.menu.main, menu)
    return true
}

override fun onOptionsItemSelected(item: MenuItem): Boolean {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    return when (item.itemId) {
        R.id.action_settings -> true
        else -> super.onOptionsItemSelected(item)
    }
}

override fun onNavigationItemSelected(item: MenuItem): Boolean {
    // Handle navigation view item clicks here.
    when (item.itemId) {
        R.id.nav_home -> {
            // Handle the camera action
            val i = Intent(Intent.ACTION_VIEW,     Uri.parse("https://www.facebook.com/brobostigon/"))
            startActivity(i)
        }
        R.id.nav_gallery -> {

        }
        R.id.nav_slideshow -> {

        }
        R.id.nav_tools -> {

        }
        R.id.nav_share -> {

        }
        R.id.nav_send -> {

        }
    }
    val drawerLayout: DrawerLayout = findViewById(R.id.drawer_layout)
    drawerLayout.closeDrawer(GravityCompat.START)
    return true
}

public fun saveStr(view: View) {
    var strength = Integer.parseInt(editText2.text.toString())
    // this should be getPreferences
    val sharedPref = this?.getPreferences(Context.MODE_PRIVATE);
    with(sharedPref.edit()) {
        putInt(getString(R.string.STR), strength)
        apply()
    }
    Toast.makeText(this, "Strength Saved", Toast.LENGTH_SHORT).show();

    //val database = FirebaseDatabase.getInstance()
    //val myRef = database.getReference("str")
    //myRef.setValue(strength)
}

public fun saveDex(view: View) {
    var dexterity = Integer.parseInt(editText.text.toString())
    // this should be getPreferences
    val sharedPref = this?.getPreferences(Context.MODE_PRIVATE);
    with(sharedPref.edit()) {
        putInt(getString(R.string.DEX), dexterity)
        apply()
    }
    Toast.makeText(this, "Dexterity Saved",     Toast.LENGTH_SHORT).show();
}

public fun saveInt(view: View) {
    var intelligance = Integer.parseInt(editText4.text.toString())
    // this should be getPreferences
    val sharedPref = this?.getPreferences(Context.MODE_PRIVATE);
    with(sharedPref.edit()) {
        putInt(getString(R.string.INT), intelligance)
        apply()
    }
    Toast.makeText(this, "Intelligence Saved", Toast.LENGTH_SHORT).show();
}

public fun saveWis(view: View) {
    var wisdom = Integer.parseInt(editText3.text.toString())
    // this should be getPreferences
    val sharedPref = this?.getPreferences(Context.MODE_PRIVATE);
    with(sharedPref.edit()) {
        putInt(getString(R.string.WIS), wisdom)
        apply()
    }
    Toast.makeText(this, "Wisdom Saved", Toast.LENGTH_SHORT).show();
}

public fun saveCha(view: View) {
    var charisma = Integer.parseInt(editText5.text.toString())
    // this should be getPreferences
    val sharedPref = this?.getPreferences(Context.MODE_PRIVATE);
    with(sharedPref.edit()) {
        putInt(getString(R.string.CHA), charisma)
        apply()
    }
    Toast.makeText(this, "charisma Saved", Toast.LENGTH_SHORT).show();
}

public fun saveCon(view: View) {
    var constitution = Integer.parseInt(editText6.text.toString())
    // this should be getPreferences
    val sharedPref = this?.getPreferences(Context.MODE_PRIVATE);
    with(sharedPref.edit()) {
        putInt(getString(R.string.CON), constitution)
        apply()
    }
    Toast.makeText(this, "Constitution Saved", Toast.LENGTH_SHORT).show();
}

public fun saveChr(view: View) {
    var chrname = editText7.text.toString()
    // this should be getPreferences
    val sharedPref = this?.getPreferences(Context.MODE_PRIVATE);
    with(sharedPref.edit()) {
        putString(getString(R.string.CHR), chrname)
        apply()
    }
    Toast.makeText(this, "Character Name Saved", Toast.LENGTH_SHORT).show();
}

    override fun onResume() {
        super.onResume()

        //public fun readSP(view: View) {

        val sharedPref = this?.getPreferences(Context.MODE_PRIVATE)

        val mystr = sharedPref.getInt(getString(R.string.STR), 0);
        editText2.setText(Integer.toString(mystr))

        val mydex = sharedPref.getInt(getString(R.string.DEX), 0);
        editText.setText(Integer.toString(mydex))

        val myint = sharedPref.getInt(getString(R.string.INT), 0);
        editText4.setText(Integer.toString(myint))

        val mywis = sharedPref.getInt(getString(R.string.WIS), 0);
        editText3.setText(Integer.toString(mywis))

        val mycon = sharedPref.getInt(getString(R.string.CON), 0);
        editText6.setText(Integer.toString(mycon))

        val mycha = sharedPref.getInt(getString(R.string.CHA), 0);
        editText5.setText(Integer.toString(mycha))

        val mychr = sharedPref.getString(getString(R.string.CHR), null);
        editText7.setText(mychr)
    }
}

2 个答案:

答案 0 :(得分:1)

您可以使用协程将数据加载到后台线程中,然后切换回UI线程以填充您的视图,如下所示(为清楚起见,我仅使用2个属性):

data class MyData(
        val myStr: Int,
        val myDex: Int
)

override fun onResume() {
    super.onResume()

    lifecycleScope.launch {
        val data = withContext(Dispatchers.IO) {
            val mystr = sharedPref.getInt(getString(R.string.STR), 0);
            val mydex = sharedPref.getInt(getString(R.string.DEX), 0);
            MyData(mystr, mydex)
        }
        editText2.setText(data.myStr.toString())
        editText.setText(data.myDex.toString())
    }
}

但是,请注意,加载首选项的速度非常快,因此我怀疑这是您的瓶颈,您可能需要进行一些分析以了解花费的时间。

还要注意,您正在混合使用processthread-您的整个应用程序都在process中运行,并且在此过程中您有多个threads-您可以切换线程在您的流程中,但您的整个应用是一个process

答案 1 :(得分:0)

使用kotlin时,您还可以使用Anko库,该库可让您使用doAsync {}在后台执行并返回到UI线程

// Example from Anko documentation
doAsync {
    // Long background task
    uiThread {
        result.text = "Done"
    }
}

检查:https://github.com/Kotlin/anko