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

≡放荡痞女 提交于 2020-01-11 07:54:14

问题


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 appreciated! My class code is below:

package com.natehoch96.widgets.iOS;

import android.appwidget.AppWidgetProvider;
import android.content.Intent;


public class Photos extends AppWidgetProvider {

    Intent myIntent = new Intent(android.provider.Settings.ACTION_SETTINGS);
    {startActivity(myIntent); }

}

回答1:


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);
    }
}



回答2:


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.



来源:https://stackoverflow.com/questions/7034873/the-method-startactivityintent-is-undefined-for-the-type

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