android widget button on press event

谁说我不能喝 提交于 2019-12-06 12:02:40

You cannot have an app widget "call "onPress" event (for example) in order to call a method inside my main activity". An app widget can invoke a PendingIntent, which means it can start an activity, start a service, or send a broadcast -- that is it. It cannot call a method within some arbitrary other object.

The closest you will be able to come is to use a distinctive Intent in the getActivity() PendingIntent (e.g., a custom action string), use setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_SINGLE_TOP) on the Intent to try to bring an existing instance of your activity forward, then check for your special Intent in both onCreate() and onNewIntent() of your activity and do whatever special thing you want done.

You can launch the new activity like this by changing your code on OnReceive Like this.

  if (intent.getAction().equals(ACTION_WIDGET_RECEIVER)) {

      Intent newIntent = new Intent("YOUR_INTENT_ACTION");   
       newIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
       context.startActivity(newIntent);

}

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!