1. 程式人生 > 程式設計 >詳解Android 程序

詳解Android 程序

多程序

如果需要的時候,app可以建立多程序。

在程序裡面

各類元件元素的清單檔案條目 、 、 和
— 均支援 android:process 屬性,此屬性可以指定該元件應在哪個程序執行。

預設程序就是主程序。其他程序一般來說都是子程序。

2個activity在不同的程序裡面,可以重新整理UI嗎?

<activity android:name=".androidsample.ActivityProgressB"
      android:process=":progressb"/>

測試結果:ActivityProgressB可以正常顯示。這個其實很好理解,如果你開啟系統相機頁面,那個activity肯定與你的app不再一個程序,但是他可以很順利的開啟,所以可以支援。

保活

OOM_ADJ

詳解Android 程序

這個就是oom 回kill程序的優先順序。

程序kill的方式

場景 介面 範圍
LowMemoryKiller LowMemoryKiller 從程序的優先順序依次kill,釋放記憶體
三方kill(無root) killbackgroundprogersss kill oom_adj>4
三方kill(有root) forcestop or kill 理論上所有,一般是非系統和可見程序
廠商kill功能 force stop or kill 理論上所有,包括native

程序保活的目的,就是提供程序的優先順序,降低程序被kill的概率。

保活的套路

開啟1個畫素的activity

2020-08-14 14:29:48.630 1164-8504/system_process W/ActivityTaskManager: Background activity start [callingPackage: com.demanmath.androidms; callingUid: 10398; isCallingUidForeground: false; isCallingUidPersistentSystemProcess: false; realCallingUid: 10398; isRealCallingUidForeground: false; isRealCallingUidPersistentSystemProcess: false; originatingPendingIntent: null; isBgStartWhitelisted: false; intent: Intent { flg=0x10000000 cmp=com.demanmath.androidms/.androidsample.LiveActivity }; callerApp: ProcessRecord{a168b71 2429:com.demanmath.androidms/u0a398}]

在android Q以後,不允許後臺程序啟動後臺頁面了。也就是想啟動一個前臺頁面

使用前臺服務

package com.demanmath.androidms.androidsample

import android.annotation.TargetApi
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.Service
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.Handler
import android.os.IBinder
import androidx.core.app.NotificationCompat
import com.demanmath.androidms.AppLog
import com.demanmath.androidms.R

/**
 *  @author   DemanMath
 *  @date    2020/8/14
 *
 */
class KeepLiveService:Service() {
  val NOTIFICATION_ID = 0x11
  val NOTIFICATION_CHANNEL_ID = "demanmathId"
  val channelName = "My Background Service"

  companion object {
    const val NOTIFICATION_ID = 0x11
  }
  override fun onBind(intent: Intent?): IBinder? {
    return null
  }

  override fun onCreate() {
    super.onCreate()
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
      startForeground(NOTIFICATION_ID,Notification())
    } else {
      startMyOwnForeground()
      startService(Intent(this,InnerService::class.java))
    }
  }

  @TargetApi(value = Build.VERSION_CODES.O)
  private fun startMyOwnForeground() {
    AppLog.d()
    val chan = NotificationChannel(
      NOTIFICATION_CHANNEL_ID,channelName,NotificationManager.IMPORTANCE_NONE
    )
    chan.lockscreenVisibility = Notification.VISIBILITY_PRIVATE
    val manager =
      (getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager)
    manager.createNotificationChannel(chan)
    val notificationBuilder =
      NotificationCompat.Builder(this,NOTIFICATION_CHANNEL_ID)
    val notification = notificationBuilder.setOngoing(true)
      .setSmallIcon(R.drawable.ic_launcher_background)
      .setContentTitle("App is running in background")
      .setPriority(NotificationManager.IMPORTANCE_MIN)
      .setCategory(Notification.CATEGORY_SERVICE)
      .build()
    startForeground(NOTIFICATION_ID,notification)
  }

  class InnerService : Service() {
    override fun onBind(intent: Intent): IBinder? {
      return null
    }

    override fun onCreate() {
      super.onCreate()
      //使用channeId & channelName
      //傳送與KeepLiveService中ID相同的Notification,然後將其取消並取消自己的前臺顯示
//      val builder: Notification.Builder = Notification.Builder(this)
//      builder.setSmallIcon(R.mipmap.ic_launcher)
//      startForeground(NOTIFICATION_ID,builder.build())
      Handler().postDelayed(Runnable {
        stopForeground(true)
        val manager =
          getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        manager.cancel(NOTIFICATION_ID)
        stopSelf()
      },100)
    }
  }

}

但是androidQ開始以後,禁止後臺程序開啟前臺程序,這個也是android為了省電考慮的。

多程序相互喚醒

這個就是每個app,其多個程序,如果比kill掉了,可以通過另一個喚起。從上面的前臺service的功效有些類似。

同樣的問題,android Q以後無效。

JobSchedule

package com.demanmath.androidms.jobservice

import android.app.job.JobParameters
import android.app.job.JobService
import android.content.Intent
import android.os.Handler
import android.os.Message
import android.widget.Toast
import com.demanmath.androidms.AppLog

/**
 *  @author   DemanMath
 *  @date    2020/8/20
 *
 */
class JobDemoService:JobService() {

  override fun onCreate() {
    super.onCreate()
    AppLog.i()
  }

  override fun onStartCommand(intent: Intent?,flags: Int,startId: Int): Int {
    AppLog.i()
    return super.onStartCommand(intent,flags,startId)
  }

  private var mHandler = object:Handler(){
    override fun handleMessage(msg: Message) {
      AppLog.i()
      Toast.makeText(
        applicationContext,"JobService task running",Toast.LENGTH_SHORT
      ).show()
      //請注意,我們手動呼叫了jobFinished方法。
      //當onStartJob返回true的時候,我們必須手動呼叫jobFinished方法
      //否則該應用中的其他job將不會被執行
      jobFinished(msg.obj as JobParameters,false)
    }
  }
  override fun onStartJob(params: JobParameters?): Boolean {
    AppLog.i()
    mHandler.sendMessage(Message.obtain(mHandler,1,params))
    return true
  }

  override fun onStopJob(params: JobParameters?): Boolean {
    AppLog.i()
    mHandler.removeMessages(1)
    return false
  }

}
package com.demanmath.androidms.jobservice

import android.app.job.JobInfo
import android.app.job.JobScheduler
import android.content.ComponentName
import android.content.Context
import com.demanmath.androidms.AppLog

/**
 *  @author   DemanMath
 *  @date    2020/8/20
 *
 */
class JobHelper(var context: Context) {

  lateinit var jobScheduler:JobScheduler

  fun startJob(){
    AppLog.i()
    jobScheduler = context.getSystemService(Context.JOB_SCHEDULER_SERVICE) as JobScheduler
    var builder = JobInfo.Builder(1,ComponentName(context.packageName,JobDemoService::class.java.name))

//    builder.setBackoffCriteria(1000L,JobInfo.BACKOFF_POLICY_LINEAR)
    var boolean = jobScheduler.schedule(builder.build())
    AppLog.i(boolean.toString())
  }
}

以上就是詳解Android 程序的詳細內容,更多關於Android 程序的資料請關注我們其它相關文章!