Android: 从主屏幕小部件拨打电话

4

我有一个小部件,希望当用户点击小部件时,它可以拨打特定号码的电话。我该怎么做?请帮忙。

2个回答

7
我能用这段代码使它正常工作:
 @Override
 public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
    Log.d(LOG_TAG, "onUpdate(): ");
    for (int appWidgetId : appWidgetIds) {

        Intent callIntent = new Intent(Intent.ACTION_CALL);
        callIntent.setData(Uri.parse("tel:"+number));
        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, callIntent, 0);

        // Get the layout for the App Widget and attach an on-click listener to the button
        RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.caller);
        views.setOnClickPendingIntent(R.id.callButton, pendingIntent);

        // Tell the AppWidgetManager to perform an update on the current App Widget
        appWidgetManager.updateAppWidget(appWidgetId, views);
    }
}

第一次添加小部件时会起作用吗?还是必须先启动应用程序才能触发onUpdate事件? - setzamora
它第一次会工作。当您添加小部件时,将调用“onUpdate()”函数。 - Rohith Nandakumar

4
    public static Intent newPhoneCallIntent(String phoneNumber){
     Intent callintent = new Intent(Intent.ACTION_DIAL);
     callintent.setData(Uri.parse("tel:"+phoneNumber));
     return callintent;
    }
    startActivity(newPhoneCallIntent("5555555555"));

我应该把这个添加在哪里?在 onUpdate() 函数里吗? - Rohith Nandakumar
startActivity() 抛出错误 - The method startActivity(Intent) is undefined for the type Widget - Rohith Nandakumar
@rohith 你需要从上下文中进行操作。如果是从某个按钮进行操作,尝试使用getContext().startActivity()。 - Nathan Schwermann

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接