• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Scala Context类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Scala中android.content.Context的典型用法代码示例。如果您正苦于以下问题:Scala Context类的具体用法?Scala Context怎么用?Scala Context使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了Context类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Scala代码示例。

示例1: MainActivity

//设置package包名称以及导入依赖的类
package $package$.activity


import $package$.api.UiService
import $package$.model.Ticker
import android.content.{Intent, Context}
import android.view.View
import android.widget.{TextView, ProgressBar, LinearLayout}
import macroid.FullDsl._
import macroid._
import android.app.Activity
import android.os.Bundle

class MainActivity extends Activity with Contexts[Activity] with MainActivityView with UiService {

  override def onCreate(b: Bundle): Unit = {
    super.onCreate(b)
    setTitle("Hello world, $name$!")
    setContentView(ui.get)
    update
  }

  def update = api(_.pubticker("btcusd")) mapUi updateView

  def updateView(t: Ticker) = runUi(
    lastPriceSlot <~ text("Whoa! Bitcoin price is " + t.last_price)
  )
}

trait MainActivityView {
  var lastPriceSlot = slot[TextView]

  def ui(implicit context: ActivityContext): Ui[LinearLayout] = {
    l[LinearLayout](
      w[TextView] <~ wire(lastPriceSlot)
    )
  }

} 
开发者ID:aafa,项目名称:rest-android-scala.g8,代码行数:40,代码来源:MainActivity.scala


示例2: FileManager

//设置package包名称以及导入依赖的类
package com.mishiranu.instantimage.util

import java.io.File

import android.content.Context
import android.webkit.MimeTypeMap

object FileManager {
  def cleanup(context: Context): Unit = {
    val time = System.currentTimeMillis - 24 * 60 * 60 * 1000
    Option(context.getFilesDir.listFiles).getOrElse(Array())
      .filter(_.lastModified < time)
      .foreach(_.delete())
  }

  def obtainSimpleFileName(originalUriString: String): String = {
    System.currentTimeMillis + "." + Option(originalUriString).map { uriString =>
      val index = uriString.lastIndexOf('.')
      if (index >= 0 && uriString.indexOf('/', index) == -1) uriString.substring(index + 1) else null
    }.filter(e => e != null && !e.isEmpty && e.length <= 5).getOrElse("jpeg")
  }

  case class FileItem(contentId: Int, displayName: String, file: File) {
    def mimeType: String = {
      val extension = {
        val index = displayName.lastIndexOf('.')
        if (index >= 0) displayName.substring(index + 1) else "jpeg"
      }
      Option(MimeTypeMap.getSingleton.getMimeTypeFromExtension(extension))
        .filter(_ != null)
        .filter(_.isEmpty)
        .getOrElse("image/jpeg")
    }
  }

  def obtainFile(context: Context, originalUriString: String, contentId: Int): FileItem = {
    val filesDir = context.getFilesDir
    filesDir.mkdirs()
    val displayName = contentId + "-" + obtainSimpleFileName(originalUriString)
    FileItem(contentId, displayName, new File(filesDir, displayName))
  }

  def listFiles(context: Context): List[FileItem] = {
    case class Data(file: File, splitted: Array[String])
    Option(context.getFilesDir.listFiles).getOrElse(Array())
      .map(f => Data(f, f.getName.split("-")))
      .filter(_.splitted != null)
      .filter(_.splitted.length == 2)
      .map(d => FileItem(d.splitted(0).toInt, d.splitted(1), d.file)).toList
  }

  def findFile(context: Context, contentId: Int): Option[FileItem] = {
    listFiles(context).find(_.contentId == contentId)
  }
} 
开发者ID:Mishiranu,项目名称:Instant-Image,代码行数:56,代码来源:FileManager.scala


示例3: BorderSelectorDrawable

//设置package包名称以及导入依赖的类
package com.mishiranu.instantimage.graphics

import android.content.Context
import android.graphics.{Canvas, Color, Paint}

class BorderSelectorDrawable(context: Context) extends SelectorDrawable {
  import BorderSelectorDrawable._

  private val paint = new Paint(Paint.ANTI_ALIAS_FLAG)
  paint.setColor(Color.BLACK)
  private val density = context.getResources.getDisplayMetrics.density

  private var selected = false

  override def setSelected(selected: Boolean, animated: Boolean): Unit = {
    this.selected = selected
    invalidateSelf()
  }

  override def draw(canvas: Canvas): Unit = {
    if (selected) {
      canvas.drawColor(0x7f000000)
      val bounds = getBounds
      val thickness = (THICKNESS_DP * density).toInt
      canvas.drawRect(bounds.top, bounds.left, bounds.right, bounds.top + thickness, paint)
      canvas.drawRect(bounds.bottom - thickness, bounds.left, bounds.right, bounds.bottom, paint)
      canvas.drawRect(bounds.top, bounds.left, bounds.left + thickness, bounds.bottom, paint)
      canvas.drawRect(bounds.top, bounds.right - thickness, bounds.right, bounds.bottom, paint)
    }
  }
}

object BorderSelectorDrawable {
  private val THICKNESS_DP = 2
} 
开发者ID:Mishiranu,项目名称:Instant-Image,代码行数:36,代码来源:BorderSelectorDrawable.scala


示例4: FloatingActionMenuBehavior

//设置package包名称以及导入依赖的类
package com.github.shadowsocks.widget

import android.animation.ValueAnimator
import android.content.Context
import android.support.design.widget.CoordinatorLayout
import android.support.design.widget.CoordinatorLayout.Behavior
import android.support.design.widget.Snackbar.SnackbarLayout
import android.support.v4.view.animation.FastOutSlowInInterpolator
import android.util.AttributeSet
import android.view.View
import com.github.clans.fab.FloatingActionMenu

import scala.collection.JavaConverters._


class FloatingActionMenuBehavior(context: Context, attrs: AttributeSet)
  extends Behavior[FloatingActionMenu](context, attrs) {
  private var fabTranslationYAnimator: ValueAnimator = _
  private var fabTranslationY: Float = _

  override def layoutDependsOn(parent: CoordinatorLayout, child: FloatingActionMenu, dependency: View) =
    dependency.isInstanceOf[SnackbarLayout]

  override def onDependentViewChanged(parent: CoordinatorLayout, child: FloatingActionMenu, dependency: View) = {
    dependency match {
      case _: SnackbarLayout =>
        var targetTransY = parent.getDependencies(child).asScala
          .filter(view => view.isInstanceOf[SnackbarLayout] && parent.doViewsOverlap(child, view))
          .map(view => view.getTranslationY - view.getHeight).reduceOption(_ min _).getOrElse(0F)
        if (targetTransY > 0) targetTransY = 0
        if (fabTranslationY != targetTransY) {
          val currentTransY = child.getTranslationY
          if (fabTranslationYAnimator != null && fabTranslationYAnimator.isRunning) fabTranslationYAnimator.cancel
          if (child.isShown && Math.abs(currentTransY - targetTransY) > child.getHeight * 0.667F) {
            if (fabTranslationYAnimator == null) {
              fabTranslationYAnimator = new ValueAnimator
              fabTranslationYAnimator.setInterpolator(new FastOutSlowInInterpolator)
              fabTranslationYAnimator.addUpdateListener(animation =>
                child.setTranslationY(animation.getAnimatedValue.asInstanceOf[Float]))
            }
            fabTranslationYAnimator.setFloatValues(currentTransY, targetTransY)
            fabTranslationYAnimator.start
          } else child.setTranslationY(targetTransY)
          fabTranslationY = targetTransY
        }
    }
    false
  }

  override def onStartNestedScroll(parent: CoordinatorLayout, child: FloatingActionMenu, directTargetChild: View,
                                   target: View, nestedScrollAxes: Int) = true
  override def onNestedScroll(parent: CoordinatorLayout, child: FloatingActionMenu, target: View, dxConsumed: Int,
                              dyConsumed: Int, dxUnconsumed: Int, dyUnconsumed: Int) = {
    super.onNestedScroll(parent, child, target, dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed)
    val dy = dyConsumed + dyUnconsumed
    if (child.isMenuButtonHidden) {
      if (dy < 0) child.showMenuButton(true)
    } else if (dy > 0) child.hideMenuButton(true)
  }
} 
开发者ID:mmmyc,项目名称:ssr-android,代码行数:61,代码来源:FloatingActionMenuBehavior.scala


示例5: NumberPickerPreferenceDialogFragment

//设置package包名称以及导入依赖的类
package be.mygod.preference

import android.content.Context
import android.support.v14.preference.PreferenceDialogFragment
import android.view.{View, ViewGroup}

class NumberPickerPreferenceDialogFragment extends PreferenceDialogFragment {
  private lazy val preference = getPreference.asInstanceOf[NumberPickerPreference]
  private lazy val picker = preference.picker

  override protected def onCreateDialogView(context: Context) = {
    val parent = picker.getParent.asInstanceOf[ViewGroup]
    if (parent != null) parent.removeView(picker)
    picker
  }

  override protected def onBindDialogView(view: View) {
    super.onBindDialogView(view)
    picker.setValue(preference.getValue)
  }

  override protected def needInputMethod = true

  def onDialogClosed(positiveResult: Boolean) {
    picker.clearFocus // commit changes
    if (positiveResult) {
      val value = picker.getValue
      if (preference.callChangeListener(value)) preference.setValue(value)
    }
  }
} 
开发者ID:RoomArchitect,项目名称:test0000,代码行数:32,代码来源:NumberPickerPreferenceDialogFragment.scala


示例6: EditTextPreferenceDialogFragment

//设置package包名称以及导入依赖的类
package be.mygod.preference

import android.content.Context
import android.support.v14.preference.PreferenceDialogFragment
import android.view.{View, ViewGroup}

class EditTextPreferenceDialogFragment extends PreferenceDialogFragment {
  private lazy val preference = getPreference.asInstanceOf[EditTextPreference]
  private lazy val editText = preference.editText

  override protected def onCreateDialogView(context: Context) = {
    val parent = editText.getParent.asInstanceOf[ViewGroup]
    if (parent != null) parent.removeView(editText)
    editText
  }

  override protected def onBindDialogView(view: View) {
    super.onBindDialogView(view)
    editText.setText(preference.getText)
    val text = editText.getText
    if (text != null) editText.setSelection(0, text.length)
  }

  override protected def needInputMethod = true

  def onDialogClosed(positiveResult: Boolean) = if (positiveResult) {
    val value = editText.getText.toString
    if (preference.callChangeListener(value)) preference.setText(value)
  }
} 
开发者ID:RoomArchitect,项目名称:test0000,代码行数:31,代码来源:EditTextPreferenceDialogFragment.scala


示例7: EditTextPreference

//设置package包名称以及导入依赖的类
package be.mygod.preference

import android.content.Context
import android.support.v7.preference.{EditTextPreference => Parent}
import android.support.v7.widget.AppCompatEditText
import android.text.InputType
import android.util.AttributeSet


class EditTextPreference(context: Context, attrs: AttributeSet = null) extends Parent(context, attrs)
  with SummaryPreference {
  val editText = new AppCompatEditText(context, attrs)
  editText.setId(android.R.id.edit)

  override protected def getSummaryValue = {
    var text = getText
    if (text == null) text = ""
    val inputType = editText.getInputType
    if (inputType == (InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD) ||
      inputType == (InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_WEB_PASSWORD) ||
      inputType == (InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_VARIATION_PASSWORD))
      "\u2022" * text.length else text
  }

  override def setText(text: String) = {
    super.setText(text)
    notifyChanged
  }
} 
开发者ID:RoomArchitect,项目名称:test0000,代码行数:30,代码来源:EditTextPreference.scala


示例8: NumberPickerPreference

//设置package包名称以及导入依赖的类
package be.mygod.preference

import android.content.Context
import android.content.res.TypedArray
import android.support.v7.preference.DialogPreference
import android.util.AttributeSet
import android.view.ContextThemeWrapper
import android.widget.NumberPicker
import com.github.shadowsocks.R

class NumberPickerPreference(private val context: Context, attrs: AttributeSet = null)
  extends DialogPreference(context, attrs) with SummaryPreference {
  private[preference] val picker = new NumberPicker(new ContextThemeWrapper(context, R.style.NumberPickerStyle))
  private var value: Int = _

  {
    val a: TypedArray = context.obtainStyledAttributes(attrs, R.styleable.NumberPickerPreference)
    setMin(a.getInt(R.styleable.NumberPickerPreference_min, 0))
    setMax(a.getInt(R.styleable.NumberPickerPreference_max, Int.MaxValue - 1))
    a.recycle
  }

  def getValue = value
  def getMin = if (picker == null) 0 else picker.getMinValue
  def getMax = picker.getMaxValue
  def setValue(i: Int) {
    if (i == value) return
    picker.setValue(i)
    value = picker.getValue
    persistInt(value)
    notifyChanged
  }
  def setMin(value: Int) = picker.setMinValue(value)
  def setMax(value: Int) = picker.setMaxValue(value)

  override protected def onGetDefaultValue(a: TypedArray, index: Int): AnyRef =
    a.getInt(index, getMin).asInstanceOf[AnyRef]
  override protected def onSetInitialValue(restorePersistedValue: Boolean, defaultValue: Any) {
    val default = defaultValue.asInstanceOf[Int]
    setValue(if (restorePersistedValue) getPersistedInt(default) else default)
  }
  protected def getSummaryValue: AnyRef = getValue.asInstanceOf[AnyRef]
} 
开发者ID:RoomArchitect,项目名称:test0000,代码行数:44,代码来源:NumberPickerPreference.scala


示例9: AlarmBroadcastReceiver

//设置package包名称以及导入依赖的类
package com.android.perrier1034.post_it_note.receiver

import android.app.{Notification, NotificationManager, PendingIntent}
import android.content.{BroadcastReceiver, Context, Intent}
import android.support.v4.app.NotificationCompat
import android.text.TextUtils
import com.android.perrier1034.post_it_note.db.dao.{PageStore, NoteStore}
import com.android.perrier1034.post_it_note.model.NoteRealm
import com.android.perrier1034.post_it_note.ui.PageManager
import com.android.perrier1034.post_it_note.util.AlarmUtil
import com.android.perrier1034.post_it_note.{App, R}

object AlarmBroadcastReceiver {
  val KEY_INTENT_ALARM_USUAL = "KEY_INTENT_USUAL"
  val KEY_INTENT_PAGE_ORDER = "KEY_INTENT_PAGE_ORDER"
}

class AlarmBroadcastReceiver extends BroadcastReceiver {
  override def onReceive(context: Context, receivedIntent: Intent) {
    receivedIntent.getAction match {
      case Intent.ACTION_PACKAGE_REPLACED | Intent.ACTION_BOOT_COMPLETED =>
        NoteStore.rebootAlarmsRealm()

      case AlarmBroadcastReceiver.KEY_INTENT_ALARM_USUAL =>
        val id = receivedIntent.getLongExtra(AlarmUtil.alarmIntentDataKey, -1)
        val note = NoteStore.findByIdRealm(id)
        val pageOrder = PageStore .getPageOrderById(note.parentId)
        if (note.inRubbish != 1) {
          val nm = App.getInstance.getSystemService(Context.NOTIFICATION_SERVICE).asInstanceOf[NotificationManager]
          val notif = makeNotification(note, pageOrder)
          nm.notify(id.asInstanceOf[Int], notif)
        }
        NoteStore.clearAlarmRealm(id)
      case _ =>
    }
  }

  private def makeNotification(note: NoteRealm, pageOrder: Int): Notification = {
    val in = new Intent(App.getInstance, classOf[PageManager])
    in.putExtra(AlarmBroadcastReceiver.KEY_INTENT_PAGE_ORDER, pageOrder)
    val pi = PendingIntent.getActivity(App.getInstance, 0, in, PendingIntent.FLAG_UPDATE_CURRENT)
    val builder = new NotificationCompat.Builder(App.getInstance)
    val content = if (TextUtils.isEmpty(note.checkItems)) "(check list)" else note.content
    builder
      .setSmallIcon(R.drawable.ic_launcher)
      .setTicker(content)
      .setContentText(content)
      .setWhen(System.currentTimeMillis).setAutoCancel(true)
      .setContentIntent(pi)
      .setContentTitle(if (TextUtils.isEmpty(note.title)) "No title" else note.title)
      .build()
  }
} 
开发者ID:perrier1034,项目名称:Post-it-Note,代码行数:54,代码来源:AlarmBroadcastReceiver.scala


示例10: ScrollViewEx

//设置package包名称以及导入依赖的类
package com.android.perrier1034.post_it_note.ui.views

import android.util.AttributeSet
import android.content.Context
import android.view.MotionEvent
import android.widget.ScrollView

class ScrollViewEx(ctx: Context, attrs: AttributeSet) extends ScrollView(ctx, attrs) {

  val DISTANCE = 20f
  var downX = 0f
  var downY = 0f

  def this(context: Context) = this(context, null)

  
  override def onInterceptTouchEvent(event: MotionEvent): Boolean = {

    // We have to call below to do scrolling properly.
    // So anyway call it and alloc the return value
    val b = super.onInterceptTouchEvent(event)

    // save touched position when "ACTION_DOWN" !
    if (event.getAction == MotionEvent.ACTION_DOWN) {
      downX = event.getX
      downY = event.getY
    }

    // calc distance
    if (event.getAction == MotionEvent.ACTION_UP) {
      return (Math.abs(event.getY - downY) > DISTANCE) || (Math.abs(event.getX - downX) > DISTANCE)
    }

    b
  }
} 
开发者ID:perrier1034,项目名称:Post-it-Note,代码行数:37,代码来源:ScrollViewEx.scala


示例11: HackyEditText

//设置package包名称以及导入依赖的类
package com.android.perrier1034.post_it_note.ui.views

import android.graphics.Canvas
import android.os.{Looper, Handler}
import android.support.v7.widget.AppCompatEditText
import android.util.AttributeSet
import android.content.Context
import android.view.inputmethod.InputMethodManager
import com.android.perrier1034.post_it_note.App

class HackyEditText(ctx: Context, attrs: AttributeSet) extends AppCompatEditText(ctx, attrs) {

  def this(ctx: Context) = this(ctx, null)

  var isTarget = false
  setWillNotDraw(false)

  override def onDraw(canvas: Canvas ) {
    super.onDraw(canvas)

    if (isTarget) {
      isTarget = false
      requestFocus()
      // setShowSoftInputOnFocus(true)

      if (isInputMethodTarget) {
        showKeyBoard()
      } else{
        // ugly hack but I have no choice.
        // this occur when CheckListAdapter.appendNewRow() called on creating new check-list-note
        new Thread(new Runnable() {
          override def run() = {
            new Handler(Looper.getMainLooper).postDelayed(new Runnable() {
              def run() = showKeyBoard()
            }, 50)
          }
        }).start()
      }
    }
  }

  def showKeyBoard() {
    val imm = getContext.getSystemService(Context.INPUT_METHOD_SERVICE).asInstanceOf[InputMethodManager]
    imm.showSoftInput(this, InputMethodManager.SHOW_FORCED)
  }

} 
开发者ID:perrier1034,项目名称:Post-it-Note,代码行数:48,代码来源:HackyEditText.scala


示例12: HackyViewPager

//设置package包名称以及导入依赖的类
package com.android.perrier1034.post_it_note.ui.views

import android.content.Context
import android.support.v4.view.ViewPager
import android.util.AttributeSet
import android.view.MotionEvent

class HackyViewPager(ctx: Context, attrs: AttributeSet) extends ViewPager(ctx, attrs) {

  def this(context: Context) = this(context, null)

  var isLocked = false

  override def onInterceptTouchEvent(ev: MotionEvent): Boolean = {
    if (!isLocked) {
      try {
        return super.onInterceptTouchEvent(ev)
      } catch {
        case e: IllegalArgumentException =>
          e.printStackTrace()
          return false
      }
    }
    false
  }

  override def onTouchEvent(event: MotionEvent): Boolean = {
    if (!isLocked) {
      return super.onTouchEvent(event)
    }
    false
  }

  def toggleLock() {
    isLocked = !isLocked
  }

  def setLocked(b: Boolean ) {
    isLocked = b
  }
} 
开发者ID:perrier1034,项目名称:Post-it-Note,代码行数:42,代码来源:HackyViewPager.scala


示例13: DividerAdder

//设置package包名称以及导入依赖的类
package com.android.perrier1034.post_it_note.ui

import android.content.Context
import android.content.res.TypedArray
import android.graphics.drawable.Drawable
import android.graphics.{Canvas, Rect}
import android.support.v7.widget.RecyclerView

object DividerAdder {
  private val ATTRS: Array[Int] = Array[Int](android.R.attr.listDivider)
}

class DividerAdder extends RecyclerView.ItemDecoration {
  private var mDivider: Drawable = null

  def this(context: Context) {
    this()
    val array: TypedArray = context.obtainStyledAttributes(DividerAdder.ATTRS)
    mDivider = array.getDrawable(0)
    array.recycle
  }

  @SuppressWarnings(Array("deplicated"))
  override def getItemOffsets(outRect: Rect, itemPosition: Int, parent: RecyclerView) {
    outRect.set(0, 0, 0, mDivider.getIntrinsicHeight)
  }

  override def onDraw(c: Canvas, parent: RecyclerView) {
    drawVertical(c, parent)
  }

  def drawVertical(c: Canvas, parent: RecyclerView) {
    val left: Int = parent.getPaddingLeft
    val right: Int = parent.getWidth - parent.getPaddingRight
    val childCount: Int = parent.getChildCount

    for (i <- 0 until parent.getChildCount) {
      val child = parent.getChildAt(i)
      val params = child.getLayoutParams.asInstanceOf[RecyclerView.LayoutParams]
      val top = child.getBottom + params.bottomMargin
      val bottom = top + mDivider.getIntrinsicHeight
      mDivider.setBounds(left, top, right, bottom)
      mDivider.draw(c)
    }
  }
} 
开发者ID:perrier1034,项目名称:Post-it-Note,代码行数:47,代码来源:DividerAdder.scala


示例14: AlarmUtil

//设置package包名称以及导入依赖的类
package com.android.perrier1034.post_it_note.util

import java.util.{Calendar, TimeZone}

import android.app.{AlarmManager, PendingIntent}
import android.content.{Context, Intent}
import com.android.perrier1034.post_it_note.App
import com.android.perrier1034.post_it_note.receiver.AlarmBroadcastReceiver

object AlarmUtil {

  val alarmIntentDataKey = "alarmIntentDataKey "
  def set(id: Long, year: Int, month: Int, date: Int) = {
    val cal = Calendar.getInstance
    cal.setTimeInMillis(System.currentTimeMillis)
    cal.setTimeZone(TimeZone.getDefault)
    cal.set(Calendar.YEAR, year)
    cal.set(Calendar.MONTH, month)
    cal.set(Calendar.DAY_OF_MONTH, date)
    cal.set(Calendar.HOUR_OF_DAY, 0)
    cal.set(Calendar.MINUTE, 0)
    val intent = new Intent(App.getInstance, classOf[AlarmBroadcastReceiver])
    intent.putExtra(alarmIntentDataKey, id)
    intent.setAction(AlarmBroadcastReceiver.KEY_INTENT_ALARM_USUAL)
    val pendingIntent = PendingIntent.getBroadcast(App.getInstance, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT)
    val alarmManager = App.getInstance.getSystemService(Context.ALARM_SERVICE).asInstanceOf[AlarmManager]
    alarmManager.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis, pendingIntent)
  }

  def clear(noteId: Long) = {
    val intent = new Intent(App.getInstance, classOf[AlarmBroadcastReceiver])
    intent.putExtra(alarmIntentDataKey, noteId)
    val pendingIntent = PendingIntent.getBroadcast(App.getInstance, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT)
    val alarmManager = App.getInstance.getSystemService(Context.ALARM_SERVICE).asInstanceOf[AlarmManager]
    alarmManager.cancel(pendingIntent)
  }
} 
开发者ID:perrier1034,项目名称:Post-it-Note,代码行数:38,代码来源:AlarmUtil.scala


示例15: AndroidVaultConfigurationProvider

//设置package包名称以及导入依赖的类
package one.lockstep.vault.spi.impl.android

import java.io.File

import one.lockstep.util._
import one.lockstep.vault.spi
import android.content.Context

import scala.util.control.NonFatal

class AndroidVaultConfigurationProvider(defaultContext: => Context)
  extends spi.VaultConfigurationProvider
    with Logging {

  def nonPersistent = sys.props.get("lockstep.nonpersistent").exists(value => value.isEmpty || value == "true")
  def workDirOpt(context: Context): Option[File] =
    if (nonPersistent) {
      logger.debug("System property 'lockstep.nonpersistent' detected, vault will not be persisted.")
      None
    } else {
      val workDir = context.getDir("lockstep", Context.MODE_PRIVATE)
      logger.debug("setting work directory to " + workDir)
      Some(workDir)
    }

  override def vaultConfig(): spi.VaultConfiguration =
    try {
      val context = defaultContext
      new spi.VaultConfiguration(workDirOpt(context).orNull)
    } catch {
      case NonFatal(cause) => throw new RuntimeException("vault configuration failed", cause)
    }
}

object AndroidVaultConfigurationProvider
  extends AndroidVaultConfigurationProvider(AndroidUtil.currentApplication) 
开发者ID:lockstep-one,项目名称:vault,代码行数:37,代码来源:AndroidVaultConfigurationProvider.scala


示例16: AndroidUtil

//设置package包名称以及导入依赖的类
package one.lockstep.vault.spi.impl.android

import java.io.InputStream
import java.lang.reflect.InvocationTargetException

import one.lockstep.util.Logging
import android.content.Context
import android.content.res.AssetManager

object AndroidUtil extends Logging {

  def currentApplication: Context =
    try {
      val activityThreadClass = Class.forName("android.app.ActivityThread")
      val currentApplicationMethod = activityThreadClass.getMethod("currentApplication")
      val currentApplication = currentApplicationMethod.invoke(null).asInstanceOf[Context]
      currentApplication
    } catch {
      case [email protected](_: ClassNotFoundException | _: NoSuchMethodException |
                  _: IllegalAccessException | _: InvocationTargetException) =>
        throw new RuntimeException("failed to determine current application context", cause)
    }

  def openAsset(context: Context, assetName: String): InputStream =
    context.getAssets.open(assetName, AssetManager.ACCESS_BUFFER)

  def assetExists(context: Context, assetName: String): Boolean = {
    val segments = assetName.split("/")
    val (path, name) = (segments.init.mkString("/"), segments.last)
    context.getAssets.list(path).contains(name)
  }

} 
开发者ID:lockstep-one,项目名称:vault,代码行数:34,代码来源:AndroidUtil.scala


示例17: VideoTranscoderTest

//设置package包名称以及导入依赖的类
package com.waz

import java.io.File
import java.util.concurrent.CountDownLatch

import android.content.Context
import android.net.Uri
import android.support.test.InstrumentationRegistry
import android.support.test.runner.AndroidJUnit4
import com.waz.api.AssetFactory.LoadCallback
import com.waz.api.{AssetFactory, AssetForUpload}
import com.waz.bitmap.video.VideoTranscoder
import com.waz.service.ZMessaging
import com.waz.threading.Threading
import org.junit.runner.RunWith
import org.junit.{Assert, Before, Test}

import scala.concurrent.Await
import scala.concurrent.duration._

@RunWith(classOf[AndroidJUnit4])
class VideoTranscoderTest {

  @Before def setUp(): Unit = {
    Threading.AssertsEnabled = false
    ZMessaging.onCreate(context)
  }

  @Test def audioTranscodingFrom8kHz(): Unit = {
    val transcoder = VideoTranscoder(context)
    val out = File.createTempFile("video", ".mp4", context.getCacheDir)

    val future = transcoder(Uri.parse("content://com.waz.test/8khz.mp4"), out, { _ => })

    Assert.assertEquals(out, Await.result(future, 15.seconds))
  }

  @Test def assetLoadingWithNoAudio(): Unit = {
    val latch = new CountDownLatch(1)
    var asset = Option.empty[AssetForUpload]

    AssetFactory.videoAsset(Uri.parse("content://com.waz.test/no_audio.mp4"), new LoadCallback {
      override def onLoaded(a: AssetForUpload): Unit = {
        asset = Some(a)
        latch.countDown()

      }
      override def onFailed(): Unit = {
        println(s"transcode failed")
        latch.countDown()
      }
    })

    latch.await()
    Assert.assertTrue(asset.isDefined)
  }

  def context: Context = instr.getTargetContext
  def instr = InstrumentationRegistry.getInstrumentation
} 
开发者ID:wireapp,项目名称:wire-android-sync-engine,代码行数:61,代码来源:VideoTranscoderTest.scala


示例18: AssetMetaDataTest

//设置package包名称以及导入依赖的类
package com.waz

import android.content.Context
import android.net.Uri
import android.support.test.InstrumentationRegistry
import android.support.test.runner.AndroidJUnit4
import com.waz.model.AssetMetaData
import com.waz.service.ZMessaging
import com.waz.threading.Threading
import com.waz.utils._
import org.junit.runner.RunWith
import org.junit.{Assert, Before, Test}

import scala.concurrent.Await
import scala.concurrent.duration._

@RunWith(classOf[AndroidJUnit4])
class AssetMetaDataTest {

  @Before def setUp(): Unit = {
    Threading.AssertsEnabled = false
    ZMessaging.onCreate(context)
  }

  @Test def testAudioDurationLoadingFromUri(): Unit = {
    val meta = Await.result(AssetMetaData.Audio(context, Uri.parse("content://com.waz.test/32kbps.m4a")), 5.seconds)

    Assert.assertEquals(309L, meta.fold2(0L, _.duration.getSeconds))
  }

  def context: Context = instr.getTargetContext
  def instr = InstrumentationRegistry.getInstrumentation
} 
开发者ID:wireapp,项目名称:wire-android-sync-engine,代码行数:34,代码来源:AssetMetaDataTest.scala


示例19: ctx

//设置package包名称以及导入依赖的类
package app.bitrader.storage

import android.content.Context
import app.bitrader._
import json.JValue



trait PreferenceStored {
  def ctx : Context

  val myClass: String = this.getClass.toString

  def save(): Unit = {
    val json: String = AppContext.jacksonMapper.writeValueAsString(this)
    ctx.saveValue(_.putString(myClass, json))
  }

  def delete(): Unit = {
    ctx.saveValue(_.remove(myClass))
  }

  def restore: Option[this.type] = {
    val string: String = ctx.preferences.getString(myClass, null)
    if (string != null) {
      val me = AppContext.jacksonMapper.readValue[this.type](string)
      Some(me)
    } else {
      None
    }
  }
} 
开发者ID:aafa,项目名称:bitrader,代码行数:33,代码来源:PreferenceStored.scala


示例20: play

//设置package包名称以及导入依赖的类
package ru.wordmetrix.dreamcrammer

import java.io._
import android.media.{MediaPlayer,AudioManager}
import ru.wordmetrix.dreamcrammer.db._
import ru.wordmetrix._
import android.app.Activity
import android.content.Context

trait PlayerBase extends Context {
    def play(word : Word) = {
        word.track match {
            case SomeData(track) => stack {
                  try {
                      val name = "%s.ogg".format(word)
                      val tmp = openFileOutput(name, Context.MODE_PRIVATE)
                      tmp.write(track)
                      tmp.close
                      new FileInputStream(getFileStreamPath(name).getPath)
                      val mediaPlayer : MediaPlayer = new MediaPlayer();

                      mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC)
                      mediaPlayer.reset()

                      mediaPlayer.setDataSource(new FileInputStream(getFileStreamPath(name).getPath).getFD())
                      mediaPlayer.prepare();
                      mediaPlayer.start();
                      Thread.sleep(mediaPlayer.getDuration());
                      mediaPlayer.release()
                  } catch {
                    case x : Throwable => log("Player fail",x)
                  }
            }
            case NoData | NeverData => {}
        }
   }
} 
开发者ID:electricmind,项目名称:dreamcrammer,代码行数:38,代码来源:playerbase.scala



注:本文中的android.content.Context类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Scala View类代码示例发布时间:2022-05-23
下一篇:
Scala Constraint类代码示例发布时间:2022-05-23
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap