/
helpers.scala
310 lines (261 loc) · 10.5 KB
/
helpers.scala
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
/*
*
*
*
*
* Scaloid: Simpler Android
*
* http://scaloid.org
*
*
*
*
*
*
* Copyright 2013 Sung-Ho Lee and Scaloid contributors
*
* Sung-Ho Lee and Scaloid contributors licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
/*
* This file is automatically generated. Any changes on this file will be OVERWRITTEN!
* To learn how to contribute, please refer to:
* https://github.com/pocorall/scaloid/wiki/Inside-Scaloid
*/
package org.scaloid.common
import android.app._
import android.content._
import android.media._
import android.net._
import android.preference._
import android.widget._
import android.view._
import scala.concurrent.Future
import scala.reflect._
import scala.util.DynamicVariable
trait AppHelpers {
/**
* Displays a simple alert dialog.
*
* Although this builder displays some UI element, this builder can be called from any thread, because the method `show()` handles threading internally.
*
* @param clickCallback This callback is run when the button is clicked. Does nothing by default.
*/
@inline def alert(title: CharSequence, text: CharSequence, clickCallback: => Unit = {})(implicit context: Context) {
new AlertDialogBuilder(title, text) {
neutralButton(android.R.string.ok, clickCallback)
}.show()
}
/**
* Launches a new activity for a give uri. For example, opens a web browser for http protocols.
*
* {{{
* openUri("http://scaloid.org")
* }}}
*/
@inline def openUri(uri: Uri)(implicit context: Context) {
context.startActivity(new Intent(Intent.ACTION_VIEW, uri))
}
@inline def pendingService(intent: Intent, flags: Int = 0)(implicit context: Context) =
PendingIntent.getService(context, 0, intent, flags)
@inline def pendingService[T](implicit context: Context, ct: ClassTag[T]) =
PendingIntent.getService(context, 0, SIntent[T], 0)
@inline def pendingActivity(intent: Intent, flags: Int = 0)(implicit context: Context) =
PendingIntent.getActivity(context, 0, intent, flags)
@inline def pendingActivity[T](implicit context: Context, ct: ClassTag[T]) =
PendingIntent.getActivity(context, 0, SIntent[T], 0)
private[scaloid] val createBundle = new DynamicVariable[Option[android.os.Bundle]](None)
}
object AppHelpers extends AppHelpers
trait ContentHelpers {
/**
* When you register BroadcastReceiver with Context.registerReceiver() you have to unregister it to prevent memory leak.
* Trait UnregisterReceiver handles these chores for you.
* All you need to do is append the trait to your class.
* {{{
* class MyService extends SService with UnregisterReceiver {
* def func() {
* // ...
* registerReceiver(receiver, intentFilter)
* // Done! automatically unregistered at UnregisterReceiverService.onDestroy()
* }
* }
* }}}
*/
def broadcastReceiver(filter: IntentFilter)(onReceiveBody: (Context, Intent) => Any)(implicit ctx: Context, reg: Registerable) {
val receiver = new BroadcastReceiver {
def onReceive(context: Context, intent: Intent) {
onReceiveBody(context, intent)
}
}
reg.onRegister(ctx.registerReceiver(receiver, filter))
reg.onUnregister(ctx.unregisterReceiver(receiver))
}
/**
* When you register BroadcastReceiver with Context.registerReceiver() you have to unregister it to prevent memory leak.
* Trait UnregisterReceiver handles these chores for you.
* All you need to do is append the trait to your class.
* {{{
* class MyService extends SService with UnregisterReceiver {
* def func() {
* // ...
* registerReceiver(receiver, intentFilter)
* // Done! automatically unregistered at UnregisterReceiverService.onDestroy()
* }
* }
* }}}
*/
def broadcastReceiver(filterString: String)(onReceiveBody: => Any)(implicit ctx: Context, reg: Registerable) {
val receiver = new BroadcastReceiver {
def onReceive(context: Context, intent: Intent) {
onReceiveBody
}
}
val filter = new IntentFilter()
filter.addAction(filterString)
reg.onRegister(ctx.registerReceiver(receiver, filter))
reg.onUnregister(ctx.unregisterReceiver(receiver))
}
}
object ContentHelpers extends ContentHelpers
trait MediaHelpers {
/**
* Plays a sound from a given Uri.
* {{{
* play("content://media/internal/audio/media/50")
* }}}
*/
def play(uri: Uri = notificationSound)(implicit context: Context) {
val r = RingtoneManager.getRingtone(context, uri)
if (r != null) {
r.play()
}
}
@inline def alarmSound: Uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM)
@inline def notificationSound: Uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
@inline def ringtoneSound: Uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE)
}
object MediaHelpers extends MediaHelpers
abstract class PreferenceVal[T](val key: String, val defaultValue: T) {
def apply(value: T)(implicit pref: SharedPreferences): T
def apply()(implicit pref: SharedPreferences): T = apply(defaultValue)
def update(value: T)(implicit pref: SharedPreferences): this.type = {
val editor = pref.edit()
put(value, editor)
editor.commit()
this
}
protected def put(value: T, editor: SharedPreferences.Editor): Unit
def remove()(implicit pref: SharedPreferences): this.type = {
pref.edit().remove(key).commit()
this
}
}
trait PreferenceHelpers {
/**
* Returns DefaultSharedPreferences object for given implicit context.
*/
@inline implicit def defaultSharedPreferences(implicit context: Context): SharedPreferences =
PreferenceManager.getDefaultSharedPreferences(context)
@inline def preferenceVal[T](key: String, defaultVal: T): PreferenceVal[T] = defaultVal match {
case v: String => new PreferenceVal[String](key, v) {
override def apply(value: String)(implicit pref: SharedPreferences): String = pref.getString(key, value)
def put(value: String, editor: SharedPreferences.Editor): Unit = editor.putString(key, value)
}.asInstanceOf[PreferenceVal[T]]
case v: Set[String] => new PreferenceVal[Set[String]](key, v) {
import scala.collection.JavaConversions._
import scala.collection.JavaConverters._
override def apply(value: Set[String])(implicit pref: SharedPreferences): Set[String] = pref.getStringSet(key, value).asScala.toSet
def put(value: Set[String], editor: SharedPreferences.Editor): Unit = editor.putStringSet(key, value)
}.asInstanceOf[PreferenceVal[T]]
case v: Int => new PreferenceVal[Int](key, v) {
override def apply(value: Int)(implicit pref: SharedPreferences): Int = pref.getInt(key, value)
def put(value: Int, editor: SharedPreferences.Editor): Unit = editor.putInt(key, value)
}.asInstanceOf[PreferenceVal[T]]
case v: Long => new PreferenceVal[Long](key, v) {
override def apply(value: Long)(implicit pref: SharedPreferences): Long = pref.getLong(key, value)
def put(value: Long, editor: SharedPreferences.Editor): Unit = editor.putLong(key, value)
}.asInstanceOf[PreferenceVal[T]]
case v: Float => new PreferenceVal[Float](key, v) {
override def apply(value: Float)(implicit pref: SharedPreferences): Float = pref.getFloat(key, value)
def put(value: Float, editor: SharedPreferences.Editor): Unit = editor.putFloat(key, value)
}.asInstanceOf[PreferenceVal[T]]
case v: Boolean => new PreferenceVal[Boolean](key, v) {
override def apply(value: Boolean)(implicit pref: SharedPreferences): Boolean = pref.getBoolean(key, value)
def put(value: Boolean, editor: SharedPreferences.Editor): Unit = editor.putBoolean(key, value)
}.asInstanceOf[PreferenceVal[T]]
case _ => throw new Exception("Invalid type for SharedPreferences")
}
import scala.language.experimental.macros
def preferenceVal[T](defaultVal: T): PreferenceVal[T] = macro PreferenceHelpers.preferenceValImpl[T]
}
object PreferenceHelpers extends PreferenceHelpers {
import scala.language.experimental.macros
import scala.reflect.macros.blackbox.Context
private def getShortName(str: String) = {
val pos = str.lastIndexOf(".")
if (pos < 0) str else str.substring(pos + 1)
}
def preferenceValImpl[T](c: Context)(defaultVal: c.Expr[T]): c.Expr[PreferenceVal[T]] = {
import c.universe._
val enclosingName = getShortName(c.internal.enclosingOwner.fullName)
val name = c.Expr[String](Literal(Constant(enclosingName)))
reify {
preferenceVal(name.splice, defaultVal.splice)
}
}
}
/**
* Contains helper methods that displaying some UI elements.
*/
trait WidgetHelpers {
@inline private[this] def _toast(message: CharSequence, duration: Int, gravity: Int, view: View)(implicit context: Context) {
runOnUiThread {
val toast = Toast.makeText(context, message, duration)
toast.setGravity(gravity, 0, 0)
if (view != null) toast.setView(view)
toast.show()
}
}
/**
* Displays a toast message.
* This method can be called from any threads.
*/
@inline def toast(message: CharSequence, gravity: Int = Gravity.BOTTOM, view: View = null)(implicit context: Context) {
_toast(message, Toast.LENGTH_SHORT, gravity, view)
}
/**
* Displays a toast message for a longer time.
* This method can be called from any threads.
*/
@inline def longToast(message: CharSequence, gravity: Int = Gravity.BOTTOM, view: View = null)(implicit context: Context) {
_toast(message, Toast.LENGTH_LONG, gravity, view)
}
/**
* Displays a dialog with spinner icon.
* This method can be called from any threads.
*/
@inline def spinnerDialog(title: CharSequence, message: CharSequence)(implicit context: Context): Future[ProgressDialog] =
evalOnUiThread(ProgressDialog.show(context, title, message, true))
}
/**
* Contains helper methods that displaying some UI elements.
*/
object WidgetHelpers extends WidgetHelpers
/**
* Aggregate trait for helpers.
*/
trait Helpers extends AppHelpers with ContentHelpers with MediaHelpers with PreferenceHelpers with WidgetHelpers
/**
* Aggregate object for helpers.
*/
object Helpers extends Helpers