Skip to content

Instantly share code, notes, and snippets.

@nicemak
Last active February 11, 2020 07:08
Show Gist options
  • Save nicemak/b4c982ac62ccae425ecfa3e5d04cea82 to your computer and use it in GitHub Desktop.
Save nicemak/b4c982ac62ccae425ecfa3e5d04cea82 to your computer and use it in GitHub Desktop.
import android.app.Activity
import android.app.ActivityManager
import android.app.Notification
import android.app.NotificationManager
import android.content.ActivityNotFoundException
import android.content.Context
import android.content.Intent
import android.content.pm.ActivityInfo
import android.graphics.*
import android.graphics.drawable.Drawable
import android.graphics.pdf.PdfDocument
import android.location.Address
import android.location.Geocoder
import android.location.Location
import android.net.ConnectivityManager
import android.net.NetworkCapabilities
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.os.PowerManager
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import android.view.inputmethod.InputMethodManager
import android.widget.Toast
import androidx.annotation.LayoutRes
import androidx.browser.customtabs.CustomTabsIntent
import androidx.core.app.NotificationCompat
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.localbroadcastmanager.content.LocalBroadcastManager
import com.boschpharma.ikonnect.utils.AppConstants.KEEP_ON
import com.boschpharma.ikonnect.utils.AppConstants.NO_SCREENSHOT
import com.boschpharma.ikonnect.utils.AppConstants.PORTRAIT
import com.google.android.gms.maps.model.BitmapDescriptor
import com.google.android.gms.maps.model.BitmapDescriptorFactory
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.io.OutputStream
import java.util.*
fun FragmentManager.getCurrentNavigationFragment(): Fragment? = primaryNavigationFragment?.childFragmentManager?.fragments?.first()
fun Context.toast(message:String) { Toast.makeText(this, message, Toast.LENGTH_LONG).show() }
fun Context.saveImageToPDF(view: View, bitmap: Bitmap, filename: String)
{
val mFolder = File(Environment.getExternalStorageDirectory().absolutePath + "/" + "iKonnect")
if (!mFolder.exists()) mFolder.mkdirs()
val mFile = File(mFolder, "$filename.pdf")
val height: Int = view.height + bitmap.height
val document = PdfDocument()
val pageInfo = PdfDocument.PageInfo.Builder(bitmap.width, height, 1).create()
val page = document.startPage(pageInfo)
val canvas: Canvas = page.canvas
view.draw(canvas)
canvas.drawBitmap(
bitmap,
null,
Rect(0, view.height, bitmap.width, bitmap.height),
null
)
document.finishPage(page)
try {
mFile.createNewFile()
val out: OutputStream = FileOutputStream(mFile)
document.writeTo(out)
document.close()
out.close()
} catch (e: Exception) {
println("Exception: $e")
}
}
fun Context.openActivity(T : Any) { startActivity(Intent(this, T::class.java)) }
fun Activity.getAddressFromLatLong(location: Location) : List<Address> {
val geoCoder = Geocoder(this, Locale.getDefault())
var addresses: List<Address> = emptyList()
try {
addresses = geoCoder.getFromLocation(location.latitude, location.longitude, 1)
} catch (ioException: IOException) {
println("Address Error: $ioException")
} catch (illegalArgumentException: IllegalArgumentException) {
println("Address Error: $illegalArgumentException")
}
return addresses
}
fun ViewGroup.inflate(@LayoutRes layoutRes: Int, attachToRoot: Boolean = false): View {
return LayoutInflater.from(context).inflate(layoutRes, this, attachToRoot)
}
fun Activity.loadDefaults() {
if (NO_SCREENSHOT) window.setFlags(WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE)
if (KEEP_ON) window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
}
fun Activity.makePortrait()
{
this.requestedOrientation = if (PORTRAIT)
ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
else
ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
}
fun Activity.makeMeTransparent() {
val uiOptions = View.SYSTEM_UI_FLAG_FULLSCREEN
window.decorView.systemUiVisibility = uiOptions
}
fun Context.hideSoftKeyboard()
{
try
{
val inputMethodManager = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
inputMethodManager.hideSoftInputFromWindow((this as Activity).currentFocus!!.windowToken, 0)
}
catch (ex: Exception) { }
}
fun Context.isNetworkAvailable(): Boolean {
val connectivityManager = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
val nw = connectivityManager.activeNetwork ?: return false
val actNw = connectivityManager.getNetworkCapabilities(nw) ?: return false
return when {
actNw.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) -> true
actNw.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) -> true
//for other device how are able to connect with Ethernet
actNw.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET) -> true
else -> false
}
} else {
val nwInfo = connectivityManager.activeNetworkInfo ?: return false
return nwInfo.isConnected
}
}
/*fun Context.getCallDetails(): String
{
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_CALL_LOG) != PackageManager.PERMISSION_GRANTED) {
return "Permission Denied For Reading Call Logs"
}
var sb = StringBuffer()
val managedCursor = contentResolver.query(CallLog.Calls.CONTENT_URI,null,null,null,null)
val name = managedCursor!!.getColumnIndex(CallLog.Calls.CACHED_NAME)
val number = managedCursor.getColumnIndex(CallLog.Calls.NUMBER)
val type = managedCursor.getColumnIndex(CallLog.Calls.TYPE)
val date = managedCursor.getColumnIndex(CallLog.Calls.DATE)
val duration = managedCursor.getColumnIndex(CallLog.Calls.DURATION)
sb.append("Call Log :")
while (managedCursor.moveToNext()) {
val storedName = managedCursor.getString(name)
val phNumber = managedCursor.getString(number)
val callType = managedCursor.getString(type)
val callDate = managedCursor.getString(date)
val callDayTime = Date(callDate.toLong())
val callDuration = managedCursor.getString(duration)
var dir = ""
val dircode = Integer.parseInt(callType)
when (dircode) {
CallLog.Calls.OUTGOING_TYPE -> dir = "OUTGOING"
CallLog.Calls.INCOMING_TYPE -> dir = "INCOMING"
CallLog.Calls.MISSED_TYPE -> dir = "MISSED"
}
sb.append("\nName:--- "+ storedName +"\nPhone Number:--- " + phNumber + "\nCall Type:--- " + dir + "\nCall Date:--- " + callDayTime + "\nCall duration in sec :--- " + callDuration)
sb.append("\n----------------------------------")
}
return if (!sb.isNullOrEmpty()) sb.toString() else ""
}*/
fun Context.bitmapDescriptorFromVector(vectorResId: Int): BitmapDescriptor? {
return ContextCompat.getDrawable(this, vectorResId)?.run {
setBounds(0, 0, intrinsicWidth, intrinsicHeight)
val bitmap = Bitmap.createBitmap(intrinsicWidth, intrinsicHeight, Bitmap.Config.ARGB_8888)
draw(Canvas(bitmap))
BitmapDescriptorFactory.fromBitmap(bitmap)
}
}
fun Activity.getScreenHeight(): Int {
val size = Point()
windowManager.defaultDisplay.getSize(size)
return size.y
}
fun Context.openPlayStore() {
try {
startActivity(Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + packageName)))
} catch (anfe: ActivityNotFoundException) {
startActivity(
Intent(
Intent.ACTION_VIEW,
Uri.parse("https://play.google.com/store/apps/details?id=" + packageName)
)
)
}
}
/** dp size to px size. */
internal fun Context.dp2Px(dp: Int): Int {
val scale = resources.displayMetrics.density
return (dp * scale).toInt()
}
/** dp size to px size. */
internal fun Context.dp2Px(dp: Float): Float {
val scale = resources.displayMetrics.density
return (dp * scale)
}
/** gets a drawable from the resource. */
internal fun Context.contextDrawable(resource: Int): Drawable? {
return ContextCompat.getDrawable(this, resource)
}
inline fun Context.notification(channelId: String, func: NotificationCompat.Builder.() -> Unit): Notification {
val builder = NotificationCompat.Builder(this, channelId)
builder.func()
return builder.build()
}
fun Context.sendLocalBroadcast(intent: Intent) {
LocalBroadcastManager.getInstance(this).sendBroadcast(intent)
}
fun Context.sendLocalBroadcastSync(intent: Intent) {
LocalBroadcastManager.getInstance(this).sendBroadcastSync(intent)
}
fun Context.openInBrowser(url: String) {
try
{
CustomTabsIntent.Builder()
.setToolbarColor(Color.BLACK)
.build()
.launchUrl(this, Uri.parse(url))
} catch (e: Exception) {
e.message?.let { toast(it) }
}
}
fun Context.isServiceRunning(serviceClass: Class<*>): Boolean {
val className = serviceClass.name
val manager = activityManager
return manager.getRunningServices(Integer.MAX_VALUE)
.any { className == it.service.className }
}
val Context.notificationManager: NotificationManager
get() = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val Context.connectivityManager: ConnectivityManager
get() = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val Context.powerManager: PowerManager
get() = getSystemService(Context.POWER_SERVICE) as PowerManager
val Context.activityManager : ActivityManager
get() = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
fun Fragment.hideKeyboard() {
view?.let { activity?.hideKeyboard(it) }
}
fun Activity.hideKeyboard() {
hideKeyboard(currentFocus ?: View(this))
}
fun Context.hideKeyboard(view: View) {
val inputMethodManager = getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
inputMethodManager.hideSoftInputFromWindow(view.windowToken, 0)
}
/**
* Extension method to dail telephone number for Context.
*/
fun Context.dialNumber(tel: String?) = startActivity(Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + tel)))
/**
* Extension method to send sms for Context.
*/
fun Context.sendSMS(phone: String?, body: String = "") {
val smsToUri = Uri.parse("smsto:" + phone)
val intent = Intent(Intent.ACTION_SENDTO, smsToUri)
intent.putExtra("sms_body", body)
startActivity(intent)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment