I have the following function pinAppWidget which I am using in MainActivity but I would need to be able to use it also in ConfigurableWidgetConfigureActivity to not have a duplicate of the function I would like to create a class that contains them.
But I'm having some problems.
Code original:
fun pinAppWidget(text: String?) {
val urlCode = extractLinks(text)
if (urlCode != "" && Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val mAppWidgetManager = getSystemService(
AppWidgetManager::class.java
)
if (!mAppWidgetManager.isRequestPinAppWidgetSupported) {
Toast.makeText(
this@MainActivity,
"Pin app widget is not supported",
Toast.LENGTH_SHORT
).show()
return
}
val myProvider = ComponentName(this@MainActivity, MyWidget::class.java)
val pinnedWidgetCallbackIntent = Intent(this@MainActivity, MyWidget::class.java)
val successCallback = PendingIntent.getBroadcast(
this@MainActivity, 0,
pinnedWidgetCallbackIntent, PendingIntent.FLAG_IMMUTABLE
)
mAppWidgetManager.requestPinAppWidget(myProvider, Bundle(), successCallback)
}
}
fun extractLinks(text: String?): String {
val index = text!!.lastIndexOf("/")
return text.substring(index + 1)
}
Class function:
import android.app.Activity
import android.app.PendingIntent
import android.appwidget.AppWidgetManager
import android.content.ComponentName
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.widget.Toast
class function : Activity() {
fun pinAppWidget(text: String?) {
val urlCode = extractLinks(text)
if (urlCode != "" && Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val mAppWidgetManager = getSystemService(
AppWidgetManager::class.java
)
if (!mAppWidgetManager.isRequestPinAppWidgetSupported) {
Toast.makeText(
this@function,
"Pin app widget is not supported",
Toast.LENGTH_SHORT
).show()
return
}
val myProvider = ComponentName(this@function, MyWidget::class.java)
val pinnedWidgetCallbackIntent = Intent(this@function, MyWidget::class.java)
val successCallback = PendingIntent.getBroadcast(
this@function, 0,
pinnedWidgetCallbackIntent, PendingIntent.FLAG_IMMUTABLE
)
mAppWidgetManager.requestPinAppWidget(myProvider, Bundle(), successCallback)
}
}
fun extractLinks(text: String?): String {
val index = text!!.lastIndexOf("/")
return text.substring(index + 1)
}
}
When I call inside the MainActivity function I get the following problem:
How can I do it, can you help me?

you could put pinAppWidget method into an object, so you can easy call it in both Activity:
Another way, you could create BaseActivity and put pinAppWidget into it. Then make your MainActivity extend BaseActivity, you can easy call pinAppWidget from here