Кнопка виджета Android на событие прессы

1

Я пытаюсь создать кнопку виджета для запуска активности приложения непосредственно через главный экран. виджет меняет изображение, когда я нажимаю его в соответствии с файлом my_button.xml. но я не могу создать событие, когда я нажимаю на него.

Мне нужно знать, как вызвать событие onPress (например), чтобы вызвать метод внутри моего основного действия. Я был бы признателен за вашу помощь.

i приложил соответствующие файлы.

widget.xml

    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_height="wrap_content" android:layout_width="wrap_content">


  <Button
        android:id="@+id/button_one"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="10dp"
        android:background="@drawable/my_button" />
</LinearLayout>

my_button.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/btn1"
          android:state_pressed="true" />
    <item android:drawable="@drawable/btn2"
          android:state_focused="true" />
    <item android:drawable="@drawable/btn3" />
</selector>

myWidgetProvider.java

package com.callsift.activity;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.RemoteViews;
import android.widget.Toast;

public class MyWidgetProvider extends AppWidgetProvider {

    public static String ACTION_WIDGET_CONFIGURE = "ConfigureWidget";
    public static String ACTION_WIDGET_RECEIVER = "ActionReceiverWidget";




        @Override
        public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
            Toast.makeText(context, "onUpdate", Toast.LENGTH_SHORT).show();

            RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget);
            Intent configIntent = new Intent(context, CallSift.class);
            configIntent.setAction(ACTION_WIDGET_CONFIGURE);

            Intent active = new Intent(context, MyWidgetProvider.class);
            active.setAction(ACTION_WIDGET_RECEIVER);
            active.putExtra("msg", "Message for Button 1");

            //PendingIntent actionPendingIntent = PendingIntent.getBroadcast(context, 0, active, 0);
            PendingIntent configPendingIntent = PendingIntent.getActivity(context, 0, configIntent, 0);

        //  remoteViews.setOnClickPendingIntent(R.id.button_one, actionPendingIntent);
            remoteViews.setOnClickPendingIntent(R.id.button_one, configPendingIntent);


            appWidgetManager.updateAppWidget(appWidgetIds, remoteViews);
        }


        @Override

        public void onReceive(Context context, Intent intent) {

            // v1.5 fix that doesn't call onDelete Action
            final String action = intent.getAction();
            if (AppWidgetManager.ACTION_APPWIDGET_DELETED.equals(action)) {
                final int appWidgetId = intent.getExtras().getInt(
                        AppWidgetManager.EXTRA_APPWIDGET_ID,
                        AppWidgetManager.INVALID_APPWIDGET_ID);
                if (appWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID) {
                    this.onDeleted(context, new int[] { appWidgetId });
                }
            } else {
                // check, if our Action was called
                if (intent.getAction().equals(ACTION_WIDGET_RECEIVER)) {
                    Toast.makeText(context, "blblbl", Toast.LENGTH_SHORT).show();
                    String msg = "null";
                    try {
                        msg = intent.getStringExtra("msg");

                    //  Toast.makeText(context, "test", Toast.LENGTH_SHORT).show();


                    } catch (NullPointerException e) {
                        Log.e("Error", "msg = null");
                    }
                    Toast.makeText(context, "ttttt", Toast.LENGTH_SHORT).show();

                    PendingIntent contentIntent = PendingIntent.getActivity(context, 0, intent, 0);
                    NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
                    Notification noty = new Notification(R.drawable.icon, "Button 1 clicked", System.currentTimeMillis());

                    noty.setLatestEventInfo(context, "Notice", msg, contentIntent);
                    notificationManager.notify(1, noty);

                } else {
                    // do nothing
                }

                super.onReceive(context, intent);
            }
        }
    }

androidmainfast.xml - Relavent part

        <!-- Broadcast Receiver that will process AppWidget updates -->
<receiver android:name=".MyWidgetProvider" android:label="@string/app_name">
    <intent-filter>
        <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
        <!-- Broadcast Receiver that will also process our self created action -->
            <action android:name="com.callsift.activity.MyWidgetProvider.ACTION_WIDGET_RECEIVER"/>
    </intent-filter>
    <meta-data android:name="android.appwidget.provider" android:resource="@xml/button_widget_provider" />
</receiver>
Теги:
android-widget

2 ответа

4

У вас не может быть виджет приложения "вызвать событие onPress" (например), чтобы вызвать метод внутри моего основного действия ". Виджет приложения может вызывать PendingIntent, что означает, что он может начать действие, запустить службу или отправить широковещательную рассылку - вот и все. Он не может вызывать метод внутри некоторого произвольного другого объекта.

Ближе всего вы сможете использовать отличительный Intent в getActivity() PendingIntent (например, пользовательскую строку действия), используйте setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_SINGLE_TOP) в Intent, чтобы попытаться существующий экземпляр вашей деятельности вперед, а затем проверьте свой специальный Intent как в onCreate(), так и onNewIntent() вашей деятельности и выполните любую специальную вещь, которую вы хотите сделать.

  • 0
    Большое спасибо за ваш ответ. есть ли шанс, что вы можете дать мне пример, как это сделать. (реальный код) Чен
1

Вы можете запустить новую активность, например, изменив свой код на OnReceive. Как это сделать.

  if (intent.getAction().equals(ACTION_WIDGET_RECEIVER)) {

      Intent newIntent = new Intent("YOUR_INTENT_ACTION");   
       newIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
       context.startActivity(newIntent);

}

Ещё вопросы

Сообщество Overcoder
Наверх
Меню