我们双击小部件时应该打开Android应用程序

时间:2014-11-11 17:57:27

标签: android widget

我希望我的小部件只在用户双击它时打开应用程序。我该如何实现它? 下面是我到目前为止的普通单击小部件的代码。

@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
    int[] appWidgetIds) 
{
    super.onUpdate(context, appWidgetManager, appWidgetIds);
    final int n=appWidgetIds.length;
    for(int i=0;i<n;i++)
    {   
        int awid=appWidgetIds[i];
        RemoteViews v=new RemoteViews(context.getPackageName(),R.layout.widget);
        Intent in=new Intent(context,MainActivity.class);
        PendingIntent pi=PendingIntent.getActivity(context,0,in,0);
        v.setOnClickPendingIntent(R.id.bopen, pi);
        appWidgetManager.updateAppWidget(awid,v);

    }

} 任何帮助将不胜感激。谢谢。!

1 个答案:

答案 0 :(得分:0)

试试这段代码:

public class WidgetProvider extends AppWidgetProvider {

    private static final int DOUBLE_CLICK_DELAY = 500;

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


        RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget);
        Intent intent = new Intent(context, getClass());
        intent.setAction("Click");
        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
        views.setOnClickPendingIntent(R.id.image, pendingIntent);
        appWidgetManager.updateAppWidget(appWidgetIds, views);
        context.getSharedPreferences("widget", 0).edit().putInt("clicks", 0).commit();

    }

    @Override
    public void onReceive(final Context context, Intent intent) {

        if (intent.getAction().equals("Click")) {

            int clickCount = context.getSharedPreferences("widget", Context.MODE_PRIVATE).getInt("clicks", 0);
            context.getSharedPreferences("widget", Context.MODE_PRIVATE).edit().putInt("clicks", ++clickCount).commit();

            final Handler handler = new Handler() {
                public void handleMessage(Message msg) {

                    int clickCount = context.getSharedPreferences("widget", Context.MODE_PRIVATE).getInt("clicks", 0);

                    if (clickCount > 1) Toast.makeText(context, "doubleClick", Toast.LENGTH_SHORT).show();
                    else Toast.makeText(context, "singleClick", Toast.LENGTH_SHORT).show();

                    context.getSharedPreferences("widget", Context.MODE_PRIVATE).edit().putInt("clicks", 0).commit();
                }
            };

            if (clickCount == 1) new Thread() {
                @Override
                public void run(){
                    try {
                        synchronized(this) { wait(DOUBLE_CLICK_DELAY); }
                        handler.sendEmptyMessage(0);
                    } catch(InterruptedException ex) {}
                }
            }.start();
        }

        super.onReceive(context, intent);

    }
    }

我是从this answer

获得的