单击android小部件上的imagebutton后显示简单的吐司

时间:2020-04-08 12:51:02

标签: java android widget imagebutton toast

在将动作添加到要添加到我的应用程序的主屏幕小部件中时,我需要帮助。 我已经在许多线程上寻找了解决方案,但是没有一个对我有用。

我想要做的就是在单击小部件上的图像按钮后举起一条简单的消息。 如果可行,我想在单击此按钮后运行服务意图。

如果您可以添加用Java编写的代码,我会很棒。

这是xml小部件的代码

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#09C"
    android:padding="@dimen/widget_margin">

    <ImageButton
        android:id="@+id/widget_btn"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:srcCompat="@drawable/on" />
</RelativeLayout>

这是类本身:

public class wow_shortcut extends AppWidgetProvider {

    static void updateAppWidget(Context context, AppWidgetManager appWidgetManager,
                                int appWidgetId) {

        CharSequence widgetText = wow_shortcutConfigureActivity.loadTitlePref(context, appWidgetId);
        // Construct the RemoteViews object
        RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.wow_shortcut);

        // Instruct the widget manager to update the widget
        appWidgetManager.updateAppWidget(appWidgetId, views);
    }

    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
        // There may be multiple widgets active, so update all of them
        for (int appWidgetId : appWidgetIds) {
            updateAppWidget(context, appWidgetManager, appWidgetId);
        }
    }

    @Override
    public void onDeleted(Context context, int[] appWidgetIds) {
        // When the user deletes the widget, delete the preference associated with it.
        for (int appWidgetId : appWidgetIds) {
            wow_shortcutConfigureActivity.deleteTitlePref(context, appWidgetId);
        }
    }

    @Override
    public void onEnabled(Context context) {
        // Enter relevant functionality for when the first widget is created
    }

    @Override
    public void onDisabled(Context context) {
        // Enter relevant functionality for when the last widget is disabled
    }
}


谢谢,祝你有美好的一天!

1 个答案:

答案 0 :(得分:1)

从Android启动服务

  1. 创建扩展BroadcastReceiver的类并将其添加到AndroidManifest文件。
  2. 创建一个PendingIntent开始广播。并将其附加到小部件视图。

    val intent = Intent(context, MyBroadcast::class.java)
    
    val pendingIntent = PendingIntent.getBroadcast(
        context,
        MY_REQUEST_CODE,
        intent,
        PendingIntent.FLAG_UPDATE_CURRENT
    )
    
    setOnClickPendingIntent(R.id.widget_btn, pendingIntent)
    
  3. 在您的BroadcastReceiver中,启动服务。

    class MyBroadcastReceiver : BroadcastReceiver() {
      override fun onReceive(context: Context?, intent: Intent?) {
          // Create new Intent to start your service.
      }
    }
    
  4. 由于后台限制,该服务可能已停止,您可能需要将其置于前台。

注意:代码在Kotlin中,但在Java中应该类似。

相关问题