小工具仅可以第一次点击

时间:2017-12-08 08:04:04

标签: android android-widget

我正在使用widget开发一个应用程序。当我第一次点击widget时它会起作用(开始一项活动),但是在关闭和打开屏幕后它不会启动activity。以下是我的小部件的代码:

WidgetProvider

@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {

    EmailApp.getAppComponent().inject(this);
    for (int appWidgetId : appWidgetIds) {
        updateAppWidget(context, appWidgetManager, appWidgetId);
        //updateAppWidgetCompose(context, appWidgetManager, appWidgetId);
    }

    final AlarmManager manager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    final Intent i = new Intent(context, WidgetIntentService.class);

    if (service == null) {
        service = PendingIntent.getService(context, 0, i, PendingIntent.FLAG_CANCEL_CURRENT);
    }
    manager.setRepeating(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime(), 120000, service);
    super.onUpdate(context, appWidgetManager, appWidgetIds);
}

private void updateAppWidget(Context context, AppWidgetManager appWidgetManager,
                             int appWidgetId) {
    Intent intent = null;
    // Construct the RemoteViews object
    RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.sample_widget);
    // Construct an Intent object includes web adresss.
    if(mPrefs.getUsername() != "")
        intent = new Intent(context, HomeActivity.class);
    else
        intent = new Intent(context, MainActivity.class);
    // In widget we are not allowing to use intents as usually. We have to use PendingIntent instead of 'startActivity'
    PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent,
            PendingIntent.FLAG_UPDATE_CURRENT);
    // Here the basic operations the remote view can do.
    views.setOnClickPendingIntent(R.id.mainWidgetLayout, pendingIntent);
    //views.setTextViewText(R.id.widget_folder, context.getText(R.string.boite_reception_label));
    // Instruct the widget manager to update the widget
    appWidgetManager.updateAppWidget(appWidgetId, views);
}

sample_widget

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/mainWidgetLayout"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clickable="true"
android:layout_marginTop="@dimen/widget_margin_top"
android:layout_marginLeft="@dimen/widget_margin_left"
android:layout_marginRight="@dimen/widget_margin_right"
android:layout_marginBottom="@dimen/widget_margin_bottom">

<LinearLayout
    android:id="@+id/widget_header"
    android:layout_width="match_parent"
    android:layout_height="48dp"
    android:background="@color/colorPrimary"
    style="@style/WidgetHeaderStartMargin">
    <TextView
        android:id="@+id/widget_folder"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:layout_gravity="center_vertical"
        android:freezesText="true"
        android:text="@string/widget_title"
        android:includeFontPadding="false"
        style="@style/WidgetTitle"/>

</LinearLayout>

<LinearLayout
    android:id="@+id/widget_layout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:padding="15dp"
    android:visibility="gone"
    android:background="@drawable/gradient_bg_widget_holo"
    android:gravity="center_vertical">

    <ImageView
        android:id="@+id/numberImg"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginRight="10dp"
        app:srcCompat="@drawable/apk"/>

    <TextView
        android:id="@+id/textMsg"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:textColor="@android:color/black"
        android:textStyle="bold"
        android:text="@string/no_new_message" />

</LinearLayout>
<LinearLayout
    android:id="@+id/widget_not_connected"
    android:layout_width="match_parent"
    android:layout_height="0dip"
    android:layout_weight="1"
    android:orientation="vertical"
    android:padding="15dp"
    android:visibility="gone"
    android:background="@drawable/gradient_bg_widget_holo"
    android:gravity="center_vertical|center_horizontal">

    <ImageView
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:src="@drawable/icon_deconnected"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:textColor="@android:color/black"
        android:textStyle="bold"
        android:text="@string/device_not_connected" />

</LinearLayout>

<TextView
    android:id="@+id/no_msg"
    android:layout_width="match_parent"
    android:layout_height="0dip"
    android:layout_weight="1"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:textStyle="bold"
    android:gravity="center"
    android:textColor="@android:color/black"
    android:background="@drawable/gradient_bg_widget_holo"
    android:text="@string/no_new_message"/>

AndroidManifest

<receiver android:name=".widget.MailWidgetProvider">
        <intent-filter>
            <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />

        </intent-filter>

        <meta-data
            android:name="android.appwidget.provider"
            android:resource="@xml/widget_provider" />
    </receiver>

我想了解代码中的错误或我需要在代码中添加的内容。欢迎提供各种帮助。

修改

我在AlarmManager中调用IntentService来获取更新小部件的数据。这是我的IntentService的内容

public class WidgetIntentService extends IntentService {
private String user, pass;


@Inject
PreferenceManager mPrefs;

public WidgetIntentService() {
    super(WidgetIntentService.class.getName());

}

@Override
protected void onHandleIntent(@Nullable Intent intent) {
    int count = 0;
    user = mPrefs.getUsername();
    pass = mPrefs.getPassword();

    if(InternetStateMonitor.isConnected()) {
        RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.sample_widget);
        remoteViews.setViewVisibility(R.id.widget_not_connected, View.GONE);

        if(user!="" && pass!="") {
            try {
                count = server.getCount(user, pass);
                Log.w("COUNT WIDGET",""+count);
            } catch (Exception e) {
                e.printStackTrace();
            }
            TextDrawable mDrawable = TextDrawable.builder()
                    .buildRound(""+count, Color.RED);

            if(count == 0) {
                remoteViews.setViewVisibility(R.id.widget_layout, View.GONE);
                remoteViews.setViewVisibility(R.id.no_msg, View.VISIBLE);
                //remoteViews.setTextViewText(R.id.no_msg, this.getText(R.string.no_new_message));
            } else if(count == 1) {
                remoteViews.setViewVisibility(R.id.no_msg, View.GONE);
                remoteViews.setViewVisibility(R.id.widget_layout, View.VISIBLE);
                remoteViews.setImageViewBitmap(R.id.numberImg, DrawableUtils.drawableToBitmap(mDrawable));
                remoteViews.setTextViewText(R.id.textMsg, this.getText(R.string.new_message_single));
            } else {
                remoteViews.setViewVisibility(R.id.no_msg, View.GONE);
                remoteViews.setViewVisibility(R.id.widget_layout, View.VISIBLE);

                remoteViews.setImageViewBitmap(R.id.numberImg, DrawableUtils.drawableToBitmap(mDrawable));
                remoteViews.setTextViewText(R.id.textMsg, this.getText(R.string.new_message_more));
            }
            ComponentName theWidget = new ComponentName(this, MailWidgetProvider.class);
            AppWidgetManager manager = AppWidgetManager.getInstance(this);
            manager.updateAppWidget(theWidget, remoteViews);
        } else {
            remoteViews.setViewVisibility(R.id.no_msg, View.VISIBLE);
            remoteViews.setTextViewText(R.id.no_msg, this.getText(R.string.tap_here));

            ComponentName theWidget = new ComponentName(this, MailWidgetProvider.class);
            AppWidgetManager manager = AppWidgetManager.getInstance(this);
            manager.updateAppWidget(theWidget, remoteViews);
        }



    } else {
        RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.sample_widget);
        remoteViews.setViewVisibility(R.id.widget_layout, View.GONE);
        remoteViews.setViewVisibility(R.id.no_msg, View.GONE);
        remoteViews.setViewVisibility(R.id.widget_not_connected, View.VISIBLE);

        ComponentName theWidget = new ComponentName(this, MailWidgetProvider.class);
        AppWidgetManager manager = AppWidgetManager.getInstance(this);
        manager.updateAppWidget(theWidget, remoteViews);
    }

}

}

此代码是否在widget中更改了某些内容?

1 个答案:

答案 0 :(得分:0)

您可以使用AppWidgetProvider的接收方法来启动您的活动。在每次单击操作时,您必须简单地广播一个操作消息,接收器将处理其余部分。 下面,我正在分享我用来解决类似问题的片段,

为广播操作声明一个常量String,在我的例子中,我使用add broadcast来启动一个活动。

public static final String ACTION_ADD = "com.myapplication.action.ADD";

在“updateAppWidget”方法中,使用此方法获取待定意图:

views.setOnClickPendingIntent(R.id.mainWidgetLayout, getPendingSelfIntent(context, ACTION_ADD, appWidgetId));

这是辅助方法:

private static PendingIntent getPendingSelfIntent(Context context, String action, int widgetId) {
    Intent intent = new Intent(context, MailWidgetProvider.class);
    intent.setAction(action);
    intent.putExtra("widget_id", widgetId);
    return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
}

这就是你的AppWidgetProvider接收器的样子:

@Override
public void onReceive(Context context, Intent intent) {
    if (ACTION_ADD.equals(intent.getAction())) {
        int appWidgetId = intent.getIntExtra("widget_id", 0);
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
        String content = preferences.getString(String.valueOf(appWidgetId),"0");
        Intent expenseIntent;
        if(preferences.getUsername() != "") {
            expenseIntent = new Intent(context, HomeActivity.class);
        }
        else {
            expenseIntent = new Intent(context, MainActivity.class);
        }
        expenseIntent.putExtra("widget_data", content);
        expenseIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(expenseIntent);
    } else { 
        super.onReceive(context, intent);
    }
}