我尝试做一个简单的小部件来启动外部应用程序(例如:Twitter)
我想使用Toast
消息,如果使用ActivityNotFoundException
找不到应用,但Toast不起作用。这是我在onUpdated
内的代码。
try {
// Create an Intent to launch Twitter
Intent intent3 = new Intent();
ComponentName cn3 = new ComponentName("com.twitter.android",
"com.twitter.android.MainActivity");
intent3.setComponent(cn3);
PendingIntent pending3 = PendingIntent.getActivity(context, 0,
intent3, 0);
RemoteViews views3 = new RemoteViews(context.getPackageName(), R.layout.activity_main);
views.setOnClickPendingIntent(R.id.imageView3, pending3);
appWidgetManager.updateAppWidget(currentWidgetId, views3);
} catch (ActivityNotFoundException e) {
Toast.makeText(context, "Twitter not installed", Toast.LENGTH_LONG).show();
}
答案 0 :(得分:0)
尝试:
Toast.makeText(getApplicationContext(), "Twitter not installed", Toast.LENGTH_LONG).show();
答案 1 :(得分:0)
public class MyWidgetProvider extends AppWidgetProvider {
private static String WIDGET_CLICKED = "widget_clicked";
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
for (int appWidgetId : appWidgetIds) {
Intent intent = new Intent(context, MyWidgetProvider.class);
intent.setAction(WIDGET_CLICKED);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.my_widget);
views.setOnClickPendingIntent(R.id.example_widget_button, pendingIntent);
appWidgetManager.updateAppWidget(appWidgetId, views);
}
}
@Override
public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);
if (intent.getAction().equals(WIDGET_CLICKED)) {
try {
Intent twitterIntent = new Intent(Intent.ACTION_MAIN);
twitterIntent.setClassName("com.twitter.android", "com.twitter.android.MainActivity");
twitterIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(twitterIntent);
} catch(ActivityNotFoundException e) {
Toast.makeText(context, "Twitter not installed", Toast.LENGTH_LONG).show();
}
}
}
}