Android 无法实例化活动组件信息{com.example.dip.tuneai/com.example.dip.tuneai.MainActivity}:java.lang.ClassNotFoundException
使用Kotlin构建音乐android应用程序。创建了两个.kt文件作为MainActivity和Utilities。但在AndroidManifest文件中遇到以下错误 错误:-Android 无法实例化活动组件信息{com.example.dip.tuneai/com.example.dip.tuneai.MainActivity}:java.lang.ClassNotFoundException,android,Android,使用Kotlin构建音乐android应用程序。创建了两个.kt文件作为MainActivity和Utilities。但在AndroidManifest文件中遇到以下错误 错误:- at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2977) at android.app.ActivityThread.handleLaunchActivity(ActivityThread
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2977)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3182)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1916)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6898)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:537)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
Caused by: java.lang.ClassNotFoundException: Didn't find class "com.example.dip.tuneai.MainActivity" on path: DexPathList[[zip file "/data/app/com.example.dip.tuneai-B8jZb4mao-TDK8fFECTmAQ==/base.apk"],nativeLibraryDirectories=[/data/app/com.example.dip.tuneai-B8jZb4mao-TDK8fFECTmAQ==/lib/arm64, /system/lib64]]
at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:134)
at java.lang.ClassLoader.loadClass(ClassLoader.java:379)
at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
at android.app.AppComponentFactory.instantiateActivity(AppComponentFactory.java:69)
at android.support.v4.app.CoreComponentFactory.instantiateActivity(CoreComponentFactory.java:43)
at android.app.Instrumentation.newActivity(Instrumentation.java:1232)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2965)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3182)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1916)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6898)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:537)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.dip.tuneai">
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.MEDIA_CONTENT_CONTROL"
tools:ignore="ProtectedPermissions" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="@drawable/mp"
android:label="@string/app_name"
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>
</manifest>
MainActivity.kt
package com.example.dip.songm
import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.database.Cursor
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Color
import android.media.MediaMetadataRetriever
import android.media.MediaPlayer
import android.os.Handler
import android.provider.MediaStore
import android.support.annotation.NonNull
import android.support.v4.app.ActivityCompat
import android.support.v4.content.ContextCompat
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.ImageButton
import android.widget.ImageView
import android.widget.SeekBar
import android.widget.TextView
import android.widget.Toast
import com.example.dip.tuneai.R
import com.example.dip.tuneai.Utilities
import java.io.File
import java.io.IOException
import java.util.ArrayList
import java.util.HashMap
open class MainActivity:AppCompatActivity(), MediaPlayer.OnCompletionListener, SeekBar.OnSeekBarChangeListener {
override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
// ImageButton playBtn, prevBtn, nextBtn;
private lateinit var mdTv1:TextView
private lateinit var mdTv2:TextView
private lateinit var mdTv3:TextView
private lateinit var elapsedTime:TextView
private lateinit var totalTime:TextView
private lateinit var seekBar:SeekBar
private lateinit var songIcon:ImageView
private lateinit var playBtn:ImageButton
private lateinit var nextBtn:ImageButton
private lateinit var prevBtn:ImageButton
private lateinit var mCurrentArtUrl:String
internal lateinit var metaRetriver:MediaMetadataRetriever
internal lateinit var art:ByteArray
private lateinit var mp:MediaPlayer
private lateinit var utils: Utilities
private var startTime = 0.0
private var finalTime = 0.0
private var forwardTime = 500
private var backwardTime = 500
private var currentSongIndex = 0
private var mHandler = Handler()
private var songsList = ArrayList<HashMap<String, String>>()
private var mUpdateTimeTask = object:Runnable {
public override fun run() {
var totalDuration = mp.getDuration()
var currentDuration = mp.getCurrentPosition()
// Displaying Total Duration time
totalTime.setText("" + utils.milliSecondsToTimer(totalDuration.toLong()))
// Displaying time completed playing
elapsedTime.setText("" + utils.milliSecondsToTimer(currentDuration.toLong()))
// Updating progress bar
var progress = (utils.getProgressPercentage(currentDuration.toLong(), totalDuration.toLong())) as Int
//Log.d("Progress", ""+progress);
seekBar.setProgress(progress)
// Running this thread after 100 milliseconds
mHandler.postDelayed(this, 100)
}
}
val playList:ArrayList<HashMap<String, String>>
get() {
val mCursor = getContentResolver().query(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
arrayOf<String>(MediaStore.Audio.Media.DISPLAY_NAME, MediaStore.Audio.Media.DATA, MediaStore.Audio.Media.ARTIST, MediaStore.Audio.Media.ALBUM), null, null,
"LOWER(" + MediaStore.Audio.Media.TITLE + ") ASC")
val count = mCursor.getCount()
if (mCursor.moveToFirst())
{
do
{
val song = HashMap<String, String>()
song.put("songTitle", mCursor.getString(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DISPLAY_NAME)))
song.put("songArtist", mCursor.getString(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST)))
song.put("songAlbum", mCursor.getString(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM)))
song.put("songPath", mCursor.getString(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA)))
songsList.add(song)
}
while (mCursor.moveToNext())
}
mCursor.close()
return songsList
}
protected override fun onCreate(savedInstanceState:Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
metaRetriver = MediaMetadataRetriever()
intiViews()
seekBar.setOnSeekBarChangeListener(this) // Important
mp.setOnCompletionListener(this) // Important
songsList = playList
playSong(0)
nextBtn.setOnLongClickListener(object:View.OnLongClickListener {
override fun onLongClick(view:View):Boolean {
var temp = startTime.toInt()
if ((temp + forwardTime) <= finalTime)
{
startTime = startTime + forwardTime
mp.seekTo(startTime.toInt())
Toast.makeText(getApplicationContext(), "You have Jumped forward 5 seconds", Toast.LENGTH_SHORT).show()
}
else
{
Toast.makeText(getApplicationContext(), "Cannot jump forward 5 seconds", Toast.LENGTH_SHORT).show()
}
return false
}
})
prevBtn.setOnLongClickListener(object: View.OnLongClickListener {
override fun onLongClick(view:View):Boolean {
var temp = startTime.toInt()
if ((temp - backwardTime) > 0)
{
startTime = startTime - backwardTime
mp.seekTo(startTime.toInt())
Toast.makeText(getApplicationContext(), "You have Jumped backward 5 seconds", Toast.LENGTH_SHORT).show()
}
else
{
Toast.makeText(getApplicationContext(), "Cannot jump backward 5 seconds", Toast.LENGTH_SHORT).show()
}
return false
}
})
}
private fun intiViews() {
// playBtn = (ImageButton) findViewById(R.id.btnPlay);
// prevBtn = (ImageButton) findViewById(R.id.btnPrevious);
// nextBtn = (ImageButton) findViewById(R.id.btnNext);
seekBar = findViewById(R.id.seekBar) as SeekBar
seekBar.setClickable(false)
mdTv1 = findViewById(R.id.metadata_1) as TextView
mdTv2 = findViewById(R.id.metadata_2) as TextView
mdTv3 = findViewById(R.id.metadata_3) as TextView
elapsedTime = findViewById(R.id.elapsed_time) as TextView
totalTime = findViewById(R.id.total_time) as TextView
playBtn = findViewById(R.id.btnPlay) as ImageButton
nextBtn = findViewById(R.id.btnNext) as ImageButton
prevBtn = findViewById(R.id.btnPrevious) as ImageButton
mp = MediaPlayer()
utils = Utilities()
}
fun playPause(view:View) {
if (mp.isPlaying())
{
if (mp != null)
{
mp.pause()
// Changing button image to play button
playBtn.setImageResource(R.drawable.play_button)
}
}
else
{
// Resume song
if (mp != null)
{
mp.start()
// Changing button image to pause button
playBtn.setImageResource(R.drawable.pause)
}
}
}
fun playPrevious(view:View) {
if (currentSongIndex > 0)
{
playSong(currentSongIndex - 1)
currentSongIndex = currentSongIndex - 1
}
else
{
// play last song
playSong(songsList.size - 1)
currentSongIndex = songsList.size - 1
}
}
fun playNext(view:View) {
if (currentSongIndex < (songsList.size - 1))
{
playSong(currentSongIndex + 1)
currentSongIndex = currentSongIndex + 1
}
else
{
// play first song
playSong(0)
currentSongIndex = 0
}
}
override fun onCompletion(mediaPlayer:MediaPlayer) {
if (currentSongIndex < (songsList.size - 1))
{
playSong(currentSongIndex + 1)
currentSongIndex = currentSongIndex + 1
}
else
{
// play first song
playSong(0)
currentSongIndex = 0
}
}
override fun onStartTrackingTouch(seekBar:SeekBar) {
mHandler.removeCallbacks(mUpdateTimeTask)
}
override fun onStopTrackingTouch(seekBar:SeekBar) {
mHandler.removeCallbacks(mUpdateTimeTask)
var totalDuration = mp.getDuration()
var currentPosition = utils.progressToTimer(seekBar.getProgress(), totalDuration)
// forward or backward to certain seconds
mp.seekTo(currentPosition)
// update timer progress again
updateProgressBar()
}
protected override fun onActivityResult(requestCode:Int,
resultCode:Int, data:Intent?){
super.onActivityResult(requestCode, resultCode, data)
if (resultCode == 100)
{
if (data != null) {
currentSongIndex = data.getExtras().getInt("songIndex")
}
// play selected song
playSong(currentSongIndex)
}
}
protected override fun onDestroy() {
super.onDestroy()
mp.release()
}
fun playSong(songIndex:Int) {
// Play song
try
{
mp.reset()
mp.setDataSource(songsList.get(songIndex).get("songPath"))
mp.prepare()
mp.start()
// Displaying Song title
var songTitle = songsList.get(songIndex).get("songTitle")
var songArtist = songsList.get(songIndex).get("songArtist")
var songAlbum = songsList.get(songIndex).get("songAlbum")
mdTv1.setText(songTitle)
mdTv2.setText(songArtist)
mdTv3.setText(songAlbum)
/* art = metaRetriver.getEmbeddedPicture();
Bitmap songImage = BitmapFactory .decodeByteArray(art, 0, art.length);
songIcon.setImageBitmap(songImage);
*/
// Changing Button Image to pause image
playBtn.setImageResource(R.drawable.pause)
// set Progress bar values
seekBar.setProgress(0)
seekBar.setMax(100)
// Updating progress bar
updateProgressBar()
}
catch (e:IllegalArgumentException) {
e.printStackTrace()
}
catch (e:IllegalStateException) {
e.printStackTrace()
}
catch (e:IOException) {
e.printStackTrace()
}
/* catch (Exception e) {
songIcon.setBackgroundColor(Color.GRAY);
}*/
}
fun updateProgressBar() {
mHandler.postDelayed(mUpdateTimeTask, 100)
}
}
package com.example.dip.songm
导入android.Manifest
导入android.content.Intent
导入android.content.pm.PackageManager
导入android.database.Cursor
导入android.graphics.Bitmap
导入android.graphics.BitmapFactory
导入android.graphics.Color
导入android.media.MediaMetadataRetriever
导入android.media.MediaPlayer
导入android.os.Handler
导入android.provider.MediaStore
导入android.support.annotation.NonNull
导入android.support.v4.app.ActivityCompat
导入android.support.v4.content.ContextCompat
导入android.support.v7.app.AppActivity
导入android.os.Bundle
导入android.view.view
导入android.widget.Button
导入android.widget.ImageButton
导入android.widget.ImageView
导入android.widget.SeekBar
导入android.widget.TextView
导入android.widget.Toast
导入com.example.dip.tuneai.R
导入com.example.dip.tuneai.Utilities
导入java.io.xml文件
导入java.io.IOException
导入java.util.ArrayList
导入java.util.HashMap
打开类MainActivity:AppCompatActivity(),MediaPlayer.OnCompletionListener,SeekBar.OnSeekbarChangListener{
重写已更改的进程(seekBar:seekBar?,进程:Int,fromUser:Boolean){
TODO(“未实现”)//要更改已创建函数的主体,请使用文件|设置|文件模板。
}
//ImageButton playBtn、prevBtn、nextBtn;
私有lateinit变量mdTv1:TextView
私有lateinit变量mdTv2:TextView
私有lateinit变量mdTv3:TextView
私有lateinit变量elapsedTime:TextView
私有lateinit var totalTime:TextView
私有lateinit变量seekBar:seekBar
私有lateinit var songIcon:ImageView
私有lateinit var playBtn:ImageButton
私有lateinit变量nextBtn:ImageButton
私有lateinit变量prevBtn:ImageButton
私有lateinit变量mcurrentartrl:String
内部lateinit变量MetaRetriever:MediaMetadataRetriever
内部lateinit变量艺术:ByteArray
私有lateinit var mp:MediaPlayer
私有lateinit变量utils:实用程序
私有变量startTime=0.0
私有var最终时间=0.0
专用var forwardTime=500
专用var backwardTime=500
私有变量currentSongIndex=0
私有变量mHandler=Handler()
私有变量songsList=ArrayList()
private var mUpdateTimeTask=对象:可运行{
公共超控趣味跑(){
var totalDuration=mp.getDuration()
var currentDuration=mp.getCurrentPosition()
//显示总持续时间
totalTime.setText(“+utils.毫秒计时器(totalDuration.toLong()))
//显示播放完成的时间
elapsedTime.setText(“+utils.毫秒计时器(currentDuration.toLong()))
//更新进度条
var progress=(utils.getProgressPercentage(currentDuration.toLong(),totalDuration.toLong())作为Int
//Log.d(“进度”,“进度+进度”);
seekBar.setProgress(进度)
//在100毫秒后运行此线程
mHandler.postDelayed(本,100)
}
}
val播放列表:ArrayList
得到(){
val mCursor=getContentResolver().query(
MediaStore.Audio.Media.EXTERNAL\u CONTENT\u URI,
arrayOf(MediaStore.Audio.Media.DISPLAY_NAME、MediaStore.Audio.Media.DATA、MediaStore.Audio.Media.Artister、MediaStore.Audio.Media.ALBUM)、null、null、,
“下(“+MediaStore.Audio.Media.TITLE+”)ASC”)
val count=mCursor.getCount()
if(mCursor.moveToFirst())
{
做
{
val song=HashMap()
song.put(“songTitle”,mCursor.getString(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DISPLAY_NAME)))
song.put(“songArtist”,mCursor.getString(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST)))
song.put(“songAlbum”,mCursor.getString(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM)))
song.put(“songPath”,mCursor.getString(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA)))
歌曲列表。添加(歌曲)
}
while(mCursor.moveToNext())
}
mCursor.close()
返回歌曲列表
}
创建时受保护的覆盖乐趣(savedInstanceState:Bundle?){
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
MetaRetriever=MediaMetadataRetriever()
意见()
seekBar.setonseekbarchaneglistener(此)//重要
mp.setOnCompletionListener(this)//重要
歌曲列表=播放列表
播放歌曲(0)
nextBtn.setOnLongClickListener(对象:View.OnLongClickListener{
单击(视图:视图):布尔值{
var temp=startTime.toInt()
如果((临时+转发时间)0)
{
startTime=startTime-后退时间
mp.seekTo(startTime.toInt())
Toast.makeText(getApplicationContext(),“您向后跳了5秒”,Toast.LENGTH\u SHORT.show())
}
其他的
{
Toast.makeText(getApplicationContext(),“不能向后跳5秒”,Toast.LENGTH\u SHORT.show())
}
返回错误
}
})
}
私人娱乐网站浏览次数(){
//playBtn=(图像按钮)
package com.example.dip.tuneai
class Utilities {
fun milliSecondsToTimer(milliseconds: Long): String {
var finalTimerString = ""
var secondsString = ""
// Convert total duration into time
val hours = (milliseconds / (1000 * 60 * 60)).toInt()
val minutes = (milliseconds % (1000 * 60 * 60)).toInt() / (1000 * 60)
val seconds = (milliseconds % (1000 * 60 * 60) % (1000 * 60) / 1000).toInt()
// Add hours if there
if (hours > 0) {
finalTimerString = hours.toString() + ":"
}
// Prepending 0 to seconds if it is one digit
if (seconds < 10) {
secondsString = "0$seconds"
} else {
secondsString = "" + seconds
}
finalTimerString = "$finalTimerString$minutes:$secondsString"
// return timer string
return finalTimerString
}
/**
* Function to get Progress percentage
* @param currentDuration
* @param totalDuration
*/
fun getProgressPercentage(currentDuration: Long, totalDuration: Long): Int {
var percentage: Double? = 0.toDouble()
val currentSeconds = (currentDuration / 1000).toInt().toLong()
val totalSeconds = (totalDuration / 1000).toInt().toLong()
// calculating percentage
percentage = currentSeconds.toDouble() / totalSeconds * 100
// return percentage
return percentage.toInt()
}
/**
* Function to change progress to timer
* @param progress -
* @param totalDuration
* returns current duration in milliseconds
*/
fun progressToTimer(progress: Int, totalDuration: Int): Int {
var totalDuration = totalDuration
var currentDuration = 0
totalDuration = totalDuration / 1000
currentDuration = (progress.toDouble() / 100 * totalDuration).toInt()
// return current duration in milliseconds
return currentDuration * 1000
}
}