Launching activity from widget

后端 未结 9 1166
深忆病人
深忆病人 2020-11-29 00:26

I\'m trying to do something which really ought to be quite easy, but it\'s driving me crazy. I\'m trying to launch an activity when a home screen widget is pressed, such as

9条回答
  •  庸人自扰
    2020-11-29 00:52

    I was having the same issue. I discovered that the fix is to call an update through the appwidget manager. here is an example of how to do that in onEnabled. It appears it needs to be done in both onEnabled and onUpdated so that when device is powering on your click intent is also intialized - in onUpdated the params already provide the reference to the manager, luckily.

    @Override 
        public void onEnabled(Context context) {  
              //Log.v("toggle_widget","Enabled is being called"); 
    
              AppWidgetManager mgr = AppWidgetManager.getInstance(context); 
              //retrieve a ref to the manager so we can pass a view update 
    
              Intent i = new Intent(); 
              i.setClassName("yourdoman.yourpackage", "yourdomain.yourpackage.yourclass"); 
              PendingIntent myPI = PendingIntent.getService(context, 0, i, 0); 
              //intent to start service 
    
            // Get the layout for the App Widget 
            RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.togglelayout); 
    
            //attach the click listener for the service start command intent 
            views.setOnClickPendingIntent(R.id.toggleButton, myPI); 
    
            //define the componenet for self 
            ComponentName comp = new ComponentName(context.getPackageName(), ToggleWidget.class.getName()); 
    
            //tell the manager to update all instances of the toggle widget with the click listener 
            mgr.updateAppWidget(comp, views); 
    } 
    

提交回复
热议问题