The method startActivity(Intent) is undefined for the type?

前端 未结 2 696
北荒
北荒 2021-01-16 17:18

So im trying to start an activity by pressing a widget. I keep running into the error \"The method startActivity(Intent) is undefined for the type Photos\" any help is much

相关标签:
2条回答
  • 2021-01-16 17:37

    What method have you put this code in? AppWidgetProvider does not have a startActivity() method. You need a Context for that. Several of AppWidgetProvider's callback methods give you access to a Context object, but it all really depends on what you intend to do.

    I suggest you take a look at the Android developer guide's documentation on AppWidgets here.

    0 讨论(0)
  • 2021-01-16 17:38

    You need to implement the onUpdate() and onReceive() methods in your AppWidgetProvider class, something like this:

    public void onUpdate(Context context, AppWidgetManager appWidgetManager, 
        int[] appWidgetIds) {
        final int N = appWidgetIds.length;
        for (int i=0; i<N; i++) {
            int appWidgetId = appWidgetIds[i];
    
            //Get the views for your widget layout
            RemoteViews views = new RemoteViews(context.getPackageName(), 
                R.layout.my_widget);
    
            //Create a pending intent for a widget click
            Intent intent = new Intent(context, Photos.class);
            intent.setAction("PhotosAction");
            PendingIntent pendingIntent = 
                PendintIntent.getBroadcast(context, 0, intent, 0);
            views.setOnClickPendingIntent(R.id.widget_click_view, pendingIntent);
    
            appWidgetManager.updateAddWidget(appWidgetId, views);
        }
    }
    

    Then write your onReceive() method to receive the pending intent and start the relevant activity:

    public void onReceive(Context context, Intent intent) {
        super.onReceive(context, intent);
    
        if (intent.getAction().equals("PhotosAction") {
            //Received photos action action, start your target activity
            Intent i = new Intent(android.provider.Settings.ACTION_SETTINGS);
            i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(i);
        }
    }
    
    0 讨论(0)
提交回复
热议问题