播放多媒体文件
播放音频
main→assets 放置音频文件
package com.example.playaudiotest
import android.media.MediaPlayer
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
private val mediaPlayer=MediaPlayer()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
initMediaPlayer()
}
private fun initMediaPlayer() {
val assetManager=assets
val fd=assetManager.openFd("music.mp3")
mediaPlayer.setDataSource(fd.fileDescriptor,fd.startOffset,fd.length)
mediaPlayer.prepare()
play.setOnClickListener {
if(!mediaPlayer.isPlaying){
mediaPlayer.start()
}
}
pause.setOnClickListener {
if(mediaPlayer.isPlaying){
mediaPlayer.pause()
}
}
stop.setOnClickListener {
if(mediaPlayer.isPlaying){
mediaPlayer.reset()
initMediaPlayer()
}
}
}
override fun onDestroy() {
super.onDestroy()
mediaPlayer.stop()
mediaPlayer.release()
}
}
播放视频
res→raw 放置视频
package com.example.playvideotest
import android.net.Uri
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val uri= Uri.parse("android.resource://$packageName/${R.raw.video}")
videoView.setVideoURI(uri)
play.setOnClickListener {
if(!videoView.isPlaying){
videoView.start()
}
}
pause.setOnClickListener {
if(videoView.isPlaying){
videoView.pause()
}
}
replay.setOnClickListener {
if(videoView.isPlaying){
videoView.resume()
}
}
}
override fun onDestroy() {
super.onDestroy()
videoView.suspend()
}
}
在子线程中更新UI
Android 不允许在子线程中进行UI操作,但是可以通过handler来实现.
package com.example.androidthreadtest
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.Message
import kotlinx.android.synthetic.main.activity_main.*
import kotlin.concurrent.thread
class MainActivity : AppCompatActivity() {
val updateText=1
val handler=object : Handler(Looper.getMainLooper()){
override fun handleMessage(msg: Message) {
when(msg.what){
updateText -> textView.text="Nice to meet you"
}
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
changeTextBtn.setOnClickListener {
thread {
val msg=Message()
msg.what=updateText
handler.sendMessage(msg)
}
}
}
}
第一个Service
MainActivity
package com.example.servicetest
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
startServiceBtn.setOnClickListener {
val intent=Intent(this,MyService::class.java)
startService(intent)//通过intent开启服务
}
stopServiceBtn.setOnClickListener {
val intent=Intent(this,MyService::class.java)
stopService(intent)
}
}
}
MyService
package com.example.servicetest
import android.app.Service
import android.content.Intent
import android.os.IBinder
import android.util.Log
class MyService : Service() {
override fun onBind(intent: Intent): IBinder {
TODO("Return the communication channel to the service.")
}
override fun onCreate() {
super.onCreate()
Log.d("MyService","onCreate executed")
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
Log.d("MyService", "onStartCommand executed")
return super.onStartCommand(intent, flags, startId)
}
override fun onDestroy() {
super.onDestroy()
Log.d("MyService","onDestroy executed")
}
}
打印结果
Activity与Service进行通信
bindServiceBtn.setOnClickListener {
val intent=Intent(this,MyService:: class.java)
bindService(intent,connection, Context.BIND_AUTO_CREATE)
}
unbindServiceBtn.setOnClickListener {
unbindService(connection)
}
在Activity中添加两个触发按钮,用来绑定和解绑Service.
这里由于用了BIND_AUTO_CREATE参数会自动创建Service.
MyService
package com.example.servicetest
import android.app.Service
import android.content.Intent
import android.os.Binder
import android.os.IBinder
import android.util.Log
class MyService : Service() {
private val mBinder=DownloadBinder()
class DownloadBinder: Binder(){
fun startDownload(){
Log.d("MyService","startDownload executed")
}
fun getProgress(): Int{
Log.d("MyService","getProgress executed")
return 0
}
}
override fun onBind(intent: Intent): IBinder {
return mBinder
}
override fun onCreate() {
super.onCreate()
Log.d("MyService","onCreate executed")
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
Log.d("MyService", "onStartCommand executed")
return super.onStartCommand(intent, flags, startId)
}
override fun onDestroy() {
super.onDestroy()
Log.d("MyService","onDestroy executed")
}
}
lateinit var downloadBinder: MyService.DownloadBinder
private val connection=object :ServiceConnection{
override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
downloadBinder=service as MyService.DownloadBinder//传进来的对象是downloadBinder对象,因此可以向下转型.
downloadBinder.startDownload()
downloadBinder.getProgress()
}
override fun onServiceDisconnected(name: ComponentName?) {
TODO("Not yet implemented")
}
}
创建Service后会返回一个mBinder,这个mBinder(downloadBinder类 型)会被当作IBinder传到onServiceConnected ,通过向下转型后回到downloadBinder类型.然后就可以调用我们在downloadBinder中自定义的方法.
使用前台Service
package com.example.servicetest
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Service
import android.content.Context
import android.content.Intent
import android.graphics.BitmapFactory
import android.os.Binder
import android.os.Build
import android.os.IBinder
import android.util.Log
import androidx.core.app.NotificationCompat
class MyService : Service() {
private val mBinder=DownloadBinder()
class DownloadBinder: Binder(){
fun startDownload(){
Log.d("MyService","startDownload executed")
}
fun getProgress(): Int{
Log.d("MyService","getProgress executed")
return 0
}
}
override fun onBind(intent: Intent): IBinder {
return mBinder
}
override fun onCreate() {
super.onCreate()
Log.d("MyService","onCreate executed")
val manager=getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.O){
val channel=NotificationChannel("my_service","前台Service 通知",NotificationManager.IMPORTANCE_DEFAULT)
manager.createNotificationChannel(channel)
}
val intent=Intent(this,MainActivity::class.java)
val pi=PendingIntent.getActivity(this,0,intent,0)
val notification=NotificationCompat.Builder(this,"my_service")
.setContentTitle("This is content title")
.setContentText("This is content text")
.setSmallIcon(R.drawable.small_icon)
.setLargeIcon(BitmapFactory.decodeResource(resources,R.drawable.large_icon))
.setContentIntent(pi)
.build()
startForeground(1,notification)
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
Log.d("MyService", "onStartCommand executed")
return super.onStartCommand(intent, flags, startId)
}
override fun onDestroy() {
super.onDestroy()
Log.d("MyService","onDestroy executed")
}
}
使用IntentService
继承IntentService
package com.example.servicetest
import android.app.IntentService
import android.content.Intent
import android.util.Log
class MyIntentService : IntentService("MyIntentService") {
override fun onHandleIntent(intent: Intent?) {
Log.d("MyIntentService","Thread id is ${Thread.currentThread().name}")
}
override fun onDestroy() {
super.onDestroy()
Log.d("MyIntentService","onDestroy executed")
}
}
启动MyIntentService
startIntentServiceBtn.setOnClickListener {
Log.d("MainActivity","Thread id is ${Thread.currentThread().name}")
val intent=Intent(this,MyIntentService::class.java)
startService(intent)
}
WebView用法
package com.example.webview
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*
import java.lang.Exception
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
webView.settings.javaScriptEnabled=true
webView.webViewClient = object : WebViewClient() {
/**
*
* return : True(拦截WebView加载Url),False(允许WebView加载Url)
*/
override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
if(url==null){
return false
}else{
if(url.startsWith("http:")||url.startsWith("https:")){
view.loadUrl(url)
return false
}else{
try {
val intent=Intent(Intent.ACTION_VIEW)
intent.setData(Uri.parse(url))
startActivity(intent)//尝试掉用其他应用打开Url
}catch (e:Exception){
e.printStackTrace()
}
return true
}
}
}
}
webView.loadUrl("https://www.baidu.com")
}
}
为了能够解析HTTP.修改AndroidManifest.xml
android:usesCleartextTraffic="true"