Intents - jorgepascoPE/Kotlin-snippets GitHub Wiki
An intent is an abstract description of an operation to be performed. It can be used to launch an Activity (as described on this page), to send it to any interested BroadcastReceiver components, and to communicate with a background Service.
Create Intent and start activity
To create a simple intent to move from one activity to another
On sender
var fooIntent = Intent(context, fooActivity::class.java)
// Put information into the intent required by the receiver activity
fooIntent.putExtra("name1", value1)
fooIntent.putExtra("name2", value2)
startActivity(fooIntent)
On receiver
// Save information received in the intent
var fooVar = intent.getStringExtra("name1")
var fooVar2 = intent.getStringExtra("name2")
Broadcast
On Constants file
const val BROADCAST_SOME_ACTION = "BROADCAST_SOME_ACTION"
On activities
Imports
import android.support.v4.content.LocalBroadcastManager
import com.example.jorgepasco.smackapp.Utilities.BROADCAST_SOME_ACTION
Send
fun clickHandler(view: View){
val newIntent = Intent(BROADCAST_SOME_ACTION) // Create Intent with a given action
LocalBroadcastManager.getInstance(context).sendBroadcast(newIntent)
}
Receive
override fun onCreate(savedInstanceState: Bundle?) {
LocalBroadcastManager.getInstance(context).registerReceiver(customReceiver,
IntentFilter(BROADCAST_USER_DATA_CHANGE))
}
private val customReceiver = object: BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent ? ) {
// Do something
}
}