安卓给app提供了:
WebView:可以显示网页的组件,详见谷歌WebView文档
借助安卓的WebView,我们可以轻松的实现一个浏览器app。首先来看我们的布局文件activity_web.xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.sc.web.WebActivity">
<com.google.android.material.appbar.AppBarLayout
android:focusableInTouchMode="true"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<androidx.appcompat.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
app:layout_scrollFlags="scroll|enterAlways|snap">
<EditText
android:id="@+id/url_edit_text"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:inputType="textUri"/>
</androidx.appcompat.widget.Toolbar>
</com.google.android.material.appbar.AppBarLayout>
<WebView
android:id="@+id/web_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>
界面上的主角就是我们的WebView,这里除了WebView,我们还使用了Toolbar来显示我们的网页链接,并提供网页跳转、前进、后退按钮。
接下来实现WebActivity:
class WebActivity : AppCompatActivity() {
private lateinit var mWebView: WebView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_web)
val toolbar = findViewById<Toolbar>(R.id.toolbar)
setSupportActionBar(toolbar)
supportActionBar?.apply {
setDisplayHomeAsUpEnabled(true)
setHomeAsUpIndicator(R.mipmap.ic_x)
setDisplayShowTitleEnabled(false)
}
val urlEditText = findViewById<EditText>(R.id.url_edit_text)
mWebView = findViewById(R.id.web_view)
mWebView.settings.javaScriptEnabled = true
mWebView.webViewClient = object : WebViewClient() {
override fun onPageStarted(view: WebView, url: String, favicon: Bitmap?) {
super.onPageStarted(view, url, favicon)
urlEditText.setText(url)
}
override fun onPageFinished(view: WebView, url: String) {
super.onPageFinished(view, url)
urlEditText.setText(url)
}
}
val uri = intent.data
if (uri == null) {
mWebView.loadUrl("https://www.baidu.com/")
} else {
mWebView.loadUrl(uri.toString())
}
val inputMethodManager = getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
mWebView.setOnTouchListener { v, event ->
inputMethodManager.hideSoftInputFromWindow(urlEditText.applicationWindowToken, 0)
urlEditText.clearFocus()
false
}
urlEditText.setOnEditorActionListener { textView, i, keyEvent ->
inputMethodManager.hideSoftInputFromWindow(textView.applicationWindowToken, 0)
mWebView.loadUrl(urlEditText.text.toString())
false
}
mWebView.setDownloadListener { url, userAgent, contentDisposition, mimetype, contentLength ->
this@WebActivity.url = url
this@WebActivity.contentLength = contentLength
if (ContextCompat.checkSelfPermission(this@WebActivity, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this@WebActivity, arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), REQUEST_CODE_DOWNLAOD)
} else {
download()
}
}
}
private var url: String? = null
private var contentLength: Long = 0
private fun download() {
val intent = Intent(this, DownloadService::class.java)
startService(intent)
bindService(intent, object : ServiceConnection {
override fun onServiceConnected(name: ComponentName, service: IBinder) {
val downloadBinder = service as DownloadBinder
downloadBinder.startDownload(url!!, contentLength)
unbindService(this)
}
override fun onServiceDisconnected(name: ComponentName) { }
}, BIND_AUTO_CREATE)
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
when (requestCode) {
REQUEST_CODE_DOWNLAOD -> if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
download()
} else {
Toast.makeText(this, "You denied the permission", Toast.LENGTH_SHORT).show()
}
}
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.toolbar_web, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
android.R.id.home -> finish()
R.id.refresh -> mWebView.reload()
R.id.go_back -> mWebView.goBack()
R.id.go_forward -> mWebView.goForward()
}
return true
}
override fun onBackPressed() {
if (mWebView.canGoBack()) {
mWebView.goBack()
} else {
finish()
}
}
companion object {
private const val REQUEST_CODE_DOWNLAOD = 1
fun actionStart(context: Context) {
val intent = Intent(context, WebActivity::class.java)
context.startActivity(intent)
}
}
}
在onCreate中首先调用WebView的loadUrl方法进入指定的url或者,如果Activity启动时没有指定url,则进入百度页面。
如果希望其它app要打开浏览器显示指定url时可以跳转到我们的浏览器,可以在AndroidManifest.xml中为我们的WebActivity加上intent-filter:
<activity
android:name="com.sc.web.WebActivity"
android:icon="@drawable/ic_web"
android:label="@string/web"
android:launchMode="singleTask"
android:taskAffinity="com.sc.web"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="http" />
<data android:scheme="https" />
</intent-filter>
</activity>
就这样实现了一个简单的浏览器app。
源代码地址:https://github.com/SSSxCCC/SCApp
总结
安卓借助WebView可以轻松实现一个浏览器
|