Search code examples
androidandroid-activitywidget

By clicking android widget invoke some functions that are present in MainActivity


I want to know how to link widget and activity in android so that by clicking the widget only call some functios to do work but Not launch the activity something like when we click bluetooth in notification bar it just open bluetooth or close bluetooth without entering to that bluetooth app...... Thanks in advance :) UPDATED :: Below is Main Activity Code.

imageFlashlight.setOnClickListener(new View.OnClickListener() {
            @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
            @Override
            public void onClick(View view) {

                if (finalHasCameraFlash) {
                    if (flashLightStatus)
                        flashLightOff();
                    else
                        flashLightOn();
                } else {
                    Toast.makeText(MainActivity.this, "No flash available on your device",
                            Toast.LENGTH_SHORT).show();
                }
            }
        });

The Code below is my widget code...

@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
private void updateAppWidget(Context context, AppWidgetManager appWidgetManager,
                             int appWidgetId) {

    // Construct the RemoteViews object
    RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.app_widget);
    // Construct an Intent object includes web adresss.
    Intent intent = new Intent(context, MainActivity.class);

    // In widget we are not allowing to use intents as usually. We have to use PendingIntent instead of 'startActivity'
    PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);


    // Here the basic operations the remote view can do.
    views.setOnClickPendingIntent(R.id.tvWidget, pendingIntent);
    // Instruct the widget manager to update the widget
    appWidgetManager.updateAppWidget(appWidgetId, views);
}

UPDATED : As you can see i want to handle two functions by clicking the widget Without Entering to the activity just by tapping..


Solution

  • You can try sending Broadcast as

    Intent broadcastIntent=new Intent(this,BroadcastReceiver.class); //use .getBroadcast instead of getActivity and start a service when u receive this //broadcast PendingIntent pendingBroadcastIntent = PendingIntent.getBroadcast(context, 7, broadcastIntent, 0) //set this pendingIntent on widget

    the PendingIntent.getBroadcast() method will do the trick. Remember to start the service when you receive this broadcast you can also set action on the intent using broadcastIntent.setAction(YOUR_ACTION).

    Regards, Karya