What is the proper method of calling a function in my application's Activity
from a widget located on the home screen? For my example, I have a background thread that is initialized in my Activity class, and would like to be able to press the widget from the home screen to call specific functions to start/stop the thread without having to enter the application.
Below is a stripped and barebone version of the Activity I am working with:
public class MainActivity extends AppCompatActivity {
private Thread thread;
private Runnable runner;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startThread();
}
private void startThread() {
//start/restart the thread
}
public void stopThread() {
//interupt the thread
}
}
Below is the barebone code for the home screen widget:
static void updateAppWidget(Context context, AppWidgetManager appWidgetManager, int appWidgetId) {
Intent intent = new Intent(context, MainActivity.class);
intent.putExtra("Goal","Stop");
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.speed_widget);
views.setOnClickPendingIntent(R.id.widgetButton, pendingIntent);
appWidgetManager.updateAppWidget(appWidgetId, views);
}
Here is what my current best solution is: From the research I've done so far, it seems like I need to continue to use putExtra()
and then getExtra()
with the Intent that is sent from the widget, and add in a string to say whether to call startThread()
or stopThread()
based on the status of the thread. The current goal is to use it like this:
String intentGoal = getIntent().getExtras().getString("Goal");
if(intentGoal.compareTo("Stop")==0){
stopThread();
}else if(intentGoal.compareTo("Start")==0){
startThread();
}
And it would be most likely ran in an overloaded version of onNewIntent()
. However, the intent sent from the widget results in a call to onCreate()
as well, which I don't want to have happen since it would restart the thread and various other initialization code that I have will be re-ran as well. I tried setting the launchMode to singleTask, but it would still call to onCreate()
rather than only onNewIntent()
. To recap, I would like to be able to press the home screen widget, and have that start or stop the thread, or more generally call a specific function in an existing `MainActivity'.