android: app widget:: How to pass non-persistent data to service from widget
After lots of efforts in doing this, i finally asking. I have widget with textview, button and imageview. both views are loaded from preference. I am able to start myActivityA when user clicks textview and myActivityB when user clicks imageview from widget. But not able to receive onclick event (in service) for button. I am doing this in following manner.
MyWidgetProvider class
final ComponentName serviceName = new Co开发者_Python百科mponentName(context, "com.mypkg.MyService");
RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget_main);
Intent intent = new Intent(Service.TOGGLE_ACTION);
intent.setComponent(serviceName);
PendingIntent pendingIntent = PendingIntent.getService(context,0 /* no requestCode */, intent, 0 /* no flags */);
remoteViews.setOnClickPendingIntent(R.id.widget_button1, pendingIntent);
In MyService class,
// broadcast message receiver for commands to service.
private BroadcastReceiver mIntentReceiver = new BroadcastReceiver()
{
@Override
public void onReceive(Context context, Intent intent)
{
String action = intent.getAction();
String cmd = intent.getStringExtra("Command");
if (TOGGLE_ACTION.equals(action))
{
m_iKey = intent.getIntExtra("MyService.MyKey", 0);
// call functions defined in MyService.
}
}
};
My problem is i am not able to receive TOGGLE_ACTION
in service at all. OnStartCommand
is called in MyService,
Can any one suggest what could be issue?
What exactly i want from button click event is....
If service is not started (service is started in first activity, life span is now limited to activity) then start it... and TOGGLE_ACTION
should be executed.
IF service is already started(means my activity is minimized) then TOGGLE_ACTION
should be executed.
Is there any other way to achieve this? Or other way to pass some data and call some routine of service from widget?
try this,
Intent intent= new Intent(context, myActivityB.class);
PendingIntent pending=PendingIntent.getActivity(context, 0 , intent,PendingIntent.FLAG_UPDATE_CURRENT);
views.setOnClickPendingIntent(R.id.button, pending);
R.id.button this is your button Id.
精彩评论