我正在做一个批处理重命名器,并且我有一个函数来重命名我在for循环中调用的函数。 当我选择两个文件时,第二个文件将被删除,而第一个文件被重命名(如果我只选择了一个文件,它将被正确重命名) 我还没有尝试选择两个以上的文件 重命名由服务完成 在onStartCommand内部调用onDestroy是否正确? 我做到了,重命名后服务并未停止
override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {
val bundle: Bundle?=intent.extras
val pathss = bundle!!.getStringArray("path")
val namess = bundle!!.getStringArray("newname")
val resultt:MutableList<String> = mutableListOf()
val notifID = 595
val maxProgress = pathss.size
var currentProgress = 1
val inten = Intent(this, HobbiesActivity::class.java)
inten.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
val pendingIntent : PendingIntent = PendingIntent.getActivity(this,0,inten, 0)
val builderr = NotificationCompat.Builder(this, "Renamer")
.setSmallIcon(R.drawable.ic_stat_name)
.setContentTitle("Renaming " + pathss.size.toString() + " files")
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setVisibility(1)
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val name = "ChannelMain"
val descText = "Renaming Progress"
val imp = NotificationManager.IMPORTANCE_HIGH
val channel = NotificationChannel("Renamer", name, imp).apply {
description = descText
enableVibration(true)
}
val notificationManager: NotificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.createNotificationChannel(channel)
}
Toast.makeText(this,"Renaming",Toast.LENGTH_SHORT).show()
startForeground(notifID,builderr.build())
with(NotificationManagerCompat.from(this)){
builderr.setProgress(maxProgress, currentProgress, false)
notify(notifID, builderr.build())
for(i in 0 until pathss.size)
{
if(renameTarget(pathss[i],namess[i])!=0)
{
resultt.add("Failed")
}
else
{
resultt.add("Success")
}
currentProgress = i+1
builderr.setContentTitle("Renaming " + currentProgress.toString() + " of " + pathss.size.toString())
builderr.setProgress(maxProgress,currentProgress,false)
notify(notifID,builderr.build())
}
stopForeground(true)
builderr.setContentTitle("Rename Complete")
.setContentText("Renamed " + maxProgress.toString() + " files")
.setProgress(0,0,false)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setSmallIcon(R.drawable.ic_stat_name)
.setContentIntent(pendingIntent)
.setAutoCancel(true)
notify(notifID,builderr.build())
}
onDestroy()
return Service.START_STICKY
}
override fun onDestroy() {
super.onDestroy()
Toast.makeText(this,"Renaming completed",Toast.LENGTH_SHORT).show()
stopSelf()
}
}
fun renameTarget(filePath:String, newName:String):Int{
val src= File(filePath)
var ext=""
val dest: File
if(src.isFile)
{
ext=filePath.substring(filePath.lastIndexOf("."),filePath.length)
}
if(newName.isEmpty())
{
return -1
}
val temp=filePath.substring(0,filePath.lastIndexOf("/"))
dest= File("$temp/$newName$ext")
return if(src.renameTo(dest)) {
0
} else {
1
}
}