我正在尝试使用三个按钮创建一个简单的小部件,以便在单击按钮时,从小部件中拨打相应的数字。
我遇到了这个问题:Android: Making a phone call from home screen widget但是,所描述的解决方案只适用于按钮。
我想过使用switch语句使不同的按钮可以点击但是失败了!
我的问题是如何实现这种方法来处理多个按钮。
感谢。
My SimpleWidgetProvider.java
public class SimpleWidgetProvider extends AppWidgetProvider {
private static final String MyOnClick1 = "myOnClickTag1";
private static final String MyOnClick2 = "myOnClickTag2";
private static final String MyOnClick3 = "myOnClickTag3";
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
// Get all ids
ComponentName thisWidget = new ComponentName(context, SimpleWidgetProvider.class);
int[] allWidgetIds = appWidgetManager.getAppWidgetIds(thisWidget);
for (int widgetId : allWidgetIds) {
RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.simple_widget);
remoteViews.setOnClickPendingIntent(R.id.actionButton, getPendingSelfIntent(context, MyOnClick1));
remoteViews.setOnClickPendingIntent(R.id.actionButton2, getPendingSelfIntent(context, MyOnClick2));
remoteViews.setOnClickPendingIntent(R.id.actionButton3, getPendingSelfIntent(context, MyOnClick3));
/* Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:192"));
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, callIntent, 0);
// Get the layout for the App Widget and attach an on-click listener to the button
views.setOnClickPendingIntent(R.id.actionButton, pendingIntent);*/
// Tell the AppWidgetManager to perform an update on the current App Widget
appWidgetManager.updateAppWidget(appWidgetIds, remoteViews);
}
}
protected PendingIntent getPendingSelfIntent(Context context, String action) {
Intent intent = new Intent(context, getClass());
intent.setAction(action);
return PendingIntent.getBroadcast(context, 0, intent, 0);
}
@Override
public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);//add this line
if (MyOnClick1.equals(intent.getAction())) {
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:192"));
// your onClick action is here
Toast.makeText(context, "Button1", Toast.LENGTH_SHORT).show();
Log.w("Widget", "Clicked button1");
} else if (MyOnClick2.equals(intent.getAction())) {
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:193"));
Toast.makeText(context, "Button2", Toast.LENGTH_SHORT).show();
Log.w("Widget", "Clicked button2");
} else if (MyOnClick3.equals(intent.getAction())) {
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:194"));
Toast.makeText(context, "Button3", Toast.LENGTH_SHORT).show();
Log.w("Widget", "Clicked button3");
}
}