如何从android中的widget打开一个应用程序?

RMK*_*RMK 12 android

当我们在那个时候点击小部件时,我需要打开一个活动屏幕(或应用程序).如何做到这一点?

DeR*_*gan 16

您需要在窗口小部件上设置onClickpendingIntent

Intent intent = new Intent(context, ExampleActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 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.appwidget_provider_layout);
views.setOnClickPendingIntent(R.id.button, pendingIntent);
Run Code Online (Sandbox Code Playgroud)

看一下这个

在Android Widget上单击处理多个按钮


Shi*_*rur 7

在yout WidgetProvider类的onUpdate()方法中包含此代码.

for(int j = 0; j < appWidgetIds.length; j++) 
{
    int appWidgetId = appWidgetIds[j];

    try {
        Intent intent = new Intent("android.intent.action.MAIN");
        intent.addCategory("android.intent.category.LAUNCHER");

        intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
        intent.setComponent(new ComponentName("your Application package",
            "fully qualified name of main activity of the app"));
        PendingIntent pendingIntent = PendingIntent.getActivity(
            context, 0, intent, 0);
        RemoteViews views = new RemoteViews(context.getPackageName(),
            layout id);
        views.setOnClickPendingIntent(view Id on which onclick to be handled, pendingIntent);
    appWidgetManager.updateAppWidget(appWidgetId, views);
    } catch (ActivityNotFoundException e) {
            Toast.makeText(context.getApplicationContext(),
                    "There was a problem loading the application: ",
                    Toast.LENGTH_SHORT).show();
    }

}
Run Code Online (Sandbox Code Playgroud)

  • "您的应用程序包","应用程序主要活动的完全限定名称"表示`intent.setComponent(new ComponentName(context.getPackageName(),MainActivity.class.getName());` (5认同)