如何从android中的小部件中打开应用程序?

问题描述 投票:12回答:4

当时我们单击窗口小部件时,我需要打开活动屏幕(或应用程序。如何执行此操作?

android
4个回答
17
投票

您需要在窗口小部件上设置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);

签出

Processing more than one button click at Android Widget


7
投票

将此代码包含在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();
    }

}

1
投票

App Widgets的Android开发人员页面包含信息和完整的示例,其完全做到这一点:http://developer.android.com/guide/topics/appwidgets/index.html


0
投票

使用Kotlin

您需要在点击小部件视图时添加PendingIntent

remoteViews.setOnClickPendingIntent(R.id.widgetRoot, 
               PendingIntent.getActivity(context, 0, Intent(context, MainActivity::class.java), 0))

其中widgetRoot是我的小部件的父ViewGroup的ID

更新中

通常在onUpdate回调中添加待处理的意图

    override fun onUpdate(
        context: Context,
        appWidgetManager: AppWidgetManager,
        appWidgetIds: IntArray) {

        // There may be multiple widgets active, so update all of them
        val widgetIds = appWidgetManager.getAppWidgetIds( ComponentName(context, ClockWidget::class.java))
        for (appWidgetId in widgetIds) {

                // Construct the RemoteViews object
                val remoteViews = RemoteViews(context.packageName, R.layout.clock_widget)

               //Open App on Widget Click
                remoteViews.setOnClickPendingIntent(R.id.weatherRoot,  
   PendingIntent.getActivity(context, 0, Intent(context, MainActivity::class.java), 0))

                //Update Widget 
                remoteViews.setTextViewText(R.id.appWidgetText, Date().toString())
                appWidgetManager.updateAppWidget(appWidgetId, remoteViews);
            }
        }
    }
© www.soinside.com 2019 - 2024. All rights reserved.