kotlin中super.onCreate(saveInstanceState)中的illegalArgumentsException

时间:2017-05-26 03:23:32

标签: android kotlin

这是我的BaseActivity.java,我把它从java转换为kotlin:

package me.wcy.music.activity

import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.media.AudioManager
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.Toolbar
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import android.view.inputmethod.InputMethodManager
import android.widget.EditText

import me.wcy.music.R
import me.wcy.music.application.AppCache
import me.wcy.music.service.PlayService
import me.wcy.music.utils.binding.ViewBinder
import me.wcy.music.utils.permission.PermissionReq

/**
 * 基类<br></br>
 * 如果继承本类,需要在 layout 中添加 [Toolbar] ,并将 AppTheme 继承 Theme.AppCompat.NoActionBar 。
 * Created by wcy on 2015/11/26.
 */
abstract class BaseActivity : AppCompatActivity() {
    protected var mHandler = Handler(Looper.getMainLooper())

    override fun onCreate(savedInstanceState: Bundle?) {
        try{
            super.onCreate(savedInstanceState)
        }catch (e:Exception){
            e.printStackTrace()
        }


        setSystemBarTransparent()
        volumeControlStream = AudioManager.STREAM_MUSIC
    }

    override fun setContentView(layoutResID: Int) {
        super.setContentView(layoutResID)
        initView()
    }

    override fun setContentView(view: View) {
        super.setContentView(view)
        initView()
    }

    override fun setContentView(view: View, params: ViewGroup.LayoutParams) {
        super.setContentView(view, params)
        initView()
    }

    private fun initView() {
        ViewBinder.bind(this)

        val mToolbar = findViewById(R.id.toolbar) as Toolbar ?: throw IllegalStateException("Layout is required to include a Toolbar with id 'toolbar'")
        setSupportActionBar(mToolbar)
        if (supportActionBar != null) {
            supportActionBar!!.setDisplayHomeAsUpEnabled(true)
        }
    }

    override fun onStart() {
        super.onStart()
        setListener()
    }

    protected open fun setListener() {}

    val playService: PlayService
        get() {
            val playService = AppCache.playService ?: throw NullPointerException("play service is null")
            return playService
        }

    protected fun checkServiceAlive(): Boolean {
        if (AppCache.playService == null) {
            startActivity(Intent(this, SplashActivity::class.java))
            AppCache.clearStack()
            return false
        }
        return true
    }

    private fun setSystemBarTransparent() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            // LOLLIPOP解决方案
            window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_STABLE
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
            window.statusBarColor = Color.TRANSPARENT
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            // KITKAT解决方案
            window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
        }
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        if (item.itemId == android.R.id.home) {
            finish()
            return true
        }
        return super.onOptionsItemSelected(item)
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        PermissionReq.onRequestPermissionsResult(requestCode, permissions, grantResults)
    }

    fun showSoftKeyboard(editText: EditText) {
        editText.isFocusable = true
        editText.isFocusableInTouchMode = true
        editText.requestFocus()
        mHandler.postDelayed({
            val inputManager = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            inputManager.showSoftInput(editText, 0)
        }, 200L)
    }

    fun hideSoftKeyboard() {
        if (currentFocus != null) {
            val inputManager = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            inputManager.hideSoftInputFromWindow(currentFocus!!.windowToken, InputMethodManager.HIDE_NOT_ALWAYS)
        }
    }
}

我已经添加了#34; a&#34; ?在onCreate中(saveInstanceState:Bundle) 但仍然有IllegalArgumentException:指定为非null的参数为null:方法kotlin jvm.internal.Intrinsics.checkParameterIsNotNull,参数savesInstanceState

这是我的日志

W/System: ClassLoader referenced unknown path: /data/app/me.wcy.music-1/lib/arm64
W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
W/System.err: java.lang.IllegalArgumentException: Parameter specified as non-null is null: method kotlin.jvm.internal.Intrinsics.checkParameterIsNotNull, parameter savedInstanceState
W/System.err:     at me.wcy.music.application.AppCache$ActivityLifecycle.onActivityCreated(AppCache.kt)
W/System.err:     at android.app.Application.dispatchActivityCreated(Application.java:195)
W/System.err:     at android.app.Activity.onCreate(Activity.java:956)
W/System.err:     at android.support.v4.app.BaseFragmentActivityGingerbread.onCreate(BaseFragmentActivityGingerbread.java:54)
W/System.err:     at android.support.v4.app.FragmentActivity.onCreate(FragmentActivity.java:319)
W/System.err:     at android.support.v7.app.AppCompatActivity.onCreate(AppCompatActivity.java:85)
W/System.err:     at me.wcy.music.activity.BaseActivity.onCreate(BaseActivity.kt:36)
W/System.err:     at me.wcy.music.activity.SplashActivity.onCreate(SplashActivity.kt:42)
W/System.err:     at android.app.Activity.performCreate(Activity.java:6372)
W/System.err:     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1110)
W/System.err:     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2432)
W/System.err:     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2539)
W/System.err:     at android.app.ActivityThread.access$900(ActivityThread.java:168)
W/System.err:     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1378)
W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:102)
W/System.err:     at android.os.Looper.loop(Looper.java:150)
W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:5665)
W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
W/System.err:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:822)
W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:712)

这是SplashActivity:

package me.wcy.music.activity

import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.AsyncTask
import android.os.Bundle
import android.os.IBinder
import android.text.TextUtils
import android.widget.ImageView
import android.widget.TextView

import java.io.File
import java.util.Calendar

import me.wcy.music.R
import me.wcy.music.application.AppCache
import me.wcy.music.http.HttpCallback
import me.wcy.music.http.HttpClient
import me.wcy.music.model.Splash
import me.wcy.music.service.PlayService
import me.wcy.music.utils.FileUtils
import me.wcy.music.utils.Preferences
import me.wcy.music.utils.ToastUtils
import me.wcy.music.utils.binding.Bind
import me.wcy.music.utils.permission.PermissionReq
import me.wcy.music.utils.permission.PermissionResult
import me.wcy.music.utils.permission.Permissions

class SplashActivity : BaseActivity() {

    @Bind(R.id.iv_splash)
    private val ivSplash: ImageView? = null
    @Bind(R.id.tv_copyright)
    private val tvCopyright: TextView? = null
    private var mPlayServiceConnection: ServiceConnection? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_splash)

        val year = Calendar.getInstance().get(Calendar.YEAR)
        tvCopyright!!.text = getString(R.string.copyright, year)

        checkService()
    }

    private fun checkService() {
        if (AppCache.playService == null) {
            startService()
            showSplash()
            updateSplash()

            mHandler.postDelayed({ bindService() }, 1000)
        } else {
            startMusicActivity()
            finish()
        }
    }

    private fun startService() {
        val intent = Intent(this, PlayService::class.java)
        startService(intent)
    }

    private fun bindService() {
        val intent = Intent()
        intent.setClass(this, PlayService::class.java)
        mPlayServiceConnection = PlayServiceConnection()
        bindService(intent, mPlayServiceConnection, Context.BIND_AUTO_CREATE)
    }

    private inner class PlayServiceConnection : ServiceConnection {
        override fun onServiceConnected(name: ComponentName, service: IBinder) {
            val playService = (service as PlayService.PlayBinder).service
            AppCache.playService = playService
            PermissionReq.with(this@SplashActivity)
                    .permissions(*Permissions.STORAGE)
                    .result(object : PermissionResult {
                        override fun onGranted() {
                            scanMusic(playService)
                        }

                        override fun onDenied() {
                            ToastUtils.show(getString(R.string.no_permission, Permissions.STORAGE_DESC, "扫描本地歌曲"))
                            finish()
                            playService.stop()
                        }
                    })
                    .request()
        }

        override fun onServiceDisconnected(name: ComponentName) {}
    }

    private fun scanMusic(playService: PlayService) {
        object : AsyncTask<Void, Void, Void>() {

            override fun doInBackground(vararg params: Void): Void? {
                playService.updateMusicList()
                return null
            }

            override fun onPostExecute(aVoid: Void) {
                startMusicActivity()
                finish()
            }
        }.execute()
    }

    private fun showSplash() {
        val splashImg = File(FileUtils.getSplashDir(this), SPLASH_FILE_NAME)
        if (splashImg.exists()) {
            val bitmap = BitmapFactory.decodeFile(splashImg.path)
            ivSplash!!.setImageBitmap(bitmap)
        }
    }

    private fun updateSplash() {
        HttpClient.getSplash(object : HttpCallback<Splash>() {
            override fun onSuccess(response: Splash?) {
                if (response == null || TextUtils.isEmpty(response.url)) {
                    return
                }

                val url = response.url
                val lastImgUrl = Preferences.splashUrl
                if (TextUtils.equals(lastImgUrl, url)) {
                    return
                }

                HttpClient.downloadFile(url, FileUtils.getSplashDir(AppCache.context), SPLASH_FILE_NAME,
                        object : HttpCallback<File>() {
                            override fun onSuccess(file: File?) {
                                Preferences.saveSplashUrl(url)
                            }

                            override fun onFail(e: Exception?) {}
                        })
            }

            override fun onFail(e: Exception?) {}
        })
    }

    private fun startMusicActivity() {
        val intent = Intent()
        intent.setClass(this, MusicActivity::class.java)
        intent.putExtras(getIntent())
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP)
        startActivity(intent)
    }

    override fun onBackPressed() {}

    override fun onDestroy() {
        if (mPlayServiceConnection != null) {
            unbindService(mPlayServiceConnection)
        }
        super.onDestroy()
    }

    companion object {
        private val SPLASH_FILE_NAME = "splash"
    }
}

0 个答案:

没有答案