Skip to content

Instantly share code, notes, and snippets.

@soulduse
Last active October 24, 2018 09:47
Show Gist options
  • Save soulduse/c9d08f62f8210685e87cdfee23aa7ed6 to your computer and use it in GitHub Desktop.
Save soulduse/c9d08f62f8210685e87cdfee23aa7ed6 to your computer and use it in GitHub Desktop.
When I copied some text in Android, How to get copied text from listener.
<application ...>
...
<service android:name=".ClipboardService"/>
</application>
class ClipboardService: Service() {
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
val mCm = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
mCm.addPrimaryClipChangedListener {
val newClip: String? = mCm.primaryClip?.getItemAt(0)?.text.toString()
toast(newClip ?: "No data")
}
return START_STICKY
}
override fun onBind(p0: Intent?): IBinder? = null
}
inline fun Context.toast(text: String) {
Toast.makeText(this, text, Toast.LENGTH_SHORT).show()
}
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
startService(Intent(this, ClipboardService::class.java))
}
}
@soulduse
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment