android 多进程开发的基本使用

2023-03-19  本文已影响0人  别看后面有人
 fun getUid(context: Context): String? {
        var uid = ""
        try {
            val pm: PackageManager = context.getPackageManager()
            val ai = pm.getApplicationInfo("com.app.framworkdemo", PackageManager.GET_META_DATA)
            uid = ai.uid.toString()
        } catch (e: PackageManager.NameNotFoundException) {
            e.printStackTrace()
        }
        return uid
    }
  1. 验证: 首先创建application:
class ProcessApplication:Application() {
    private val TAG="m_tag"
    override fun onCreate() {
        super.onCreate()
        //获取进程Id
        //获取进程Id
        val pid = Process.myPid()
        Log.d(TAG, "ProcessApplication onCreate pid is $pid") //根据进程id获取进程名称
        val pName = getProcessName(this, pid)
        Log.d(TAG, "onCreate:${pName} ")
    }

    fun getProcessName(cxt: Context, pid: Int): String? {
        val am = cxt.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
        val runningApps = am.runningAppProcesses ?: return null
        for (procInfo in runningApps) {
            if (procInfo.pid == pid) {
                return procInfo.processName
            }
        }
        return null
    }
}
  1. 验证: 其次创建不同进程的activity:
    第一个activity的进程,android:process=":remote"
Log.d(TAG, "onCreate: ProcessOneActivity")
        val pid = Process.myPid()
        Log.d(TAG, "onCreate:ProcessOneActivity pid: $pid")
        Log.d(TAG, "onCreate:ProcessOneActivity getUid: ${getUid(this)}")
        binding.btnProcessOne.setOnClickListener {
            val intent=Intent(this,ProcessTwoActivity::class.java)
            intent.putExtra("process","进程测试")
            startActivity(intent)
        }

第二个activity的进程,android:process="com.process.two"

   val process=intent.getStringExtra("process")
        Log.d(TAG, "onCreate:ProcessTwoActivity $process")
        val pid = Process.myPid()
        Log.d(TAG, "onCreate: ProcessTwoActivity pid:$pid")
        Log.d(TAG, "onCreate:ProcessTwoActivity getUid:${getUid(this)}")

测试结果:


截屏2023-03-20 15.42.37.png
上一篇 下一篇

猜你喜欢

热点阅读