android app should open when we double tap on widget - android

I want my widget to open the application only when the user double taps on it.How do i implement it?
Below is the code for normal single tap widget which i have till now.
#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);
}
}
Any help will be appreciated.thank you.!

try this code:
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);
}
}
i get it from this answer

Related

Automatically update widget in the home screen when i make modification in my application

How can we updating the View of a Home Screen Widget on the onReceive method of AppWidgetProvider?.I am trying to update the listview of my Home screen widget but it seems that I cant access the listview of my AppWidgetProvider on onReceive method.My problem is when i changes in my application and come back to the home screen that the widget has no modification.Here is a sample code of my onReceive
public class WidgetTaskSchedular extends AppWidgetProvider {
private final String TAG = "CalendarViewSample:"
+ this.getClass().getName();
static int ID;
int[] sameid=new int[1];
#Override
public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);
if(intent.getAction().equals("update_widget"))
{
Log.i(TAG,"AppWidgetIds:"+ID);
for(int i=0;i<1;i++)
{
sameid[i]=ID;
Log.i(TAG,"SameId:"+sameid[i]);
onUpdate(context, AppWidgetManager.getInstance(context),sameid);
}
}
}
public static String EXTRA_WORD=
"com.capsone.testing.calendar.WORD";
#SuppressWarnings("deprecation")
#Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
super.onUpdate(context, appWidgetManager, appWidgetIds);
for (int i=0; i<appWidgetIds.length; i++) {
ID=appWidgetIds[i];
Log.i(TAG,"LengthofWidget:"+appWidgetIds.length);
Log.i(TAG,"TestAppWidget:"+appWidgetIds[i]);
Intent intentWidgetService=new Intent(context, WidgetService.class);
intentWidgetService.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetIds[i]);
intentWidgetService.setData(Uri.parse(intentWidgetService.toUri(Intent.URI_INTENT_SCHEME)));
RemoteViews remoteView=new RemoteViews(context.getPackageName(),
R.layout.widgetlayout);
remoteView.setRemoteAdapter(appWidgetIds[i], R.id.listWidget,
intentWidgetService);
Intent clickIntent=new Intent(context, ActionBarActivity.class);
PendingIntent clickPendingIntent=PendingIntent
.getActivity(context, 0,
clickIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
remoteView.setPendingIntentTemplate(R.id.listWidget, clickPendingIntent);
ComponentName component=new ComponentName(context,WidgetTaskSchedular.class);
appWidgetManager.updateAppWidget(component, remoteView);
}
}
}
MainActivity class:
In this main class i change some modification and broadcast this to widget class using on pause method:
#Override
public void onPause() {
super.onPause();
Intent updateWidget = new Intent(getActivity(), WidgetTaskSchedular.class);
updateWidget.setAction("update_widget");
PendingIntent pending = PendingIntent.getBroadcast(getActivity(), 0, updateWidget, PendingIntent.FLAG_CANCEL_CURRENT);
try {
pending.send();
} catch (CanceledException e) {
e.printStackTrace();
}
}

Start my application by clicking on widget

I'm trying How do I run an Activity from a button on a widget in Android? in order to launch my application on click on an image button. When i un-comment the code it switches the images but when i try to use this code it does nothing. I'd like to kick off my application instead.
public class MyWidgetIntentReceiver extends BroadcastReceiver {
private static int clickCount = 0;
#Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals("pl.looksok.intent.action.CHANGE_PICTURE")){
updateWidgetPictureAndButtonListener(context);
}
}
private void updateWidgetPictureAndButtonListener(Context context) {
Log.i("PROJECTCARUSO", "updateWidgetPictureAndButtonListener");
RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget);
// remoteViews.setImageViewResource(R.id.widget_button, getImageToSet());
//
// //REMEMBER TO ALWAYS REFRESH YOUR BUTTON CLICK LISTENERS!!!
// remoteViews.setOnClickPendingIntent(R.id.widget_button, MyWidgetProvider.buildButtonPendingIntent(context));
//
// MyWidgetProvider.pushWidgetUpdate(context.getApplicationContext(), remoteViews);
Intent intentClick = new Intent(context, FragmentChange.class);
PendingIntent pendingIntent = PendingIntent.getActivity (context, 0,
intentClick, 0);
remoteViews.setOnClickPendingIntent (R.id.widget_button, pendingIntent);
}
private int getImageToSet() {
clickCount++;
return clickCount % 2 == 0 ? R.drawable.app_icon : R.drawable.energy;
}
}
Here's what i finally got to work:
public class WidgetProvider extends AppWidgetProvider {
public static String SWITCH_WIDGET_UPDATE = "MainActivity.Switch";
#Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
Log.i("PROJECTCARUSO","onUpdate");
RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget);
remoteViews.setOnClickPendingIntent(R.id.widget_button, buildButtonPendingIntent(context));
Intent intentClick = new Intent(context, FragmentChange.class);
PendingIntent pendingIntent = PendingIntent.getActivity (context, 0, intentClick, 0);
remoteViews.setOnClickPendingIntent (R.id.widget_button, pendingIntent);
pushWidgetUpdate(context, remoteViews);
}
public static PendingIntent buildButtonPendingIntent(Context context) {
Intent intent = new Intent();
intent.setAction("CHANGE_PICTURE");
return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
}
public static void pushWidgetUpdate(Context context, RemoteViews remoteViews) {
ComponentName myWidget = new ComponentName(context, WidgetProvider.class);
AppWidgetManager manager = AppWidgetManager.getInstance(context);
manager.updateAppWidget(myWidget, remoteViews);
}
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
super.onReceive(context, intent);
}
}

Cant change ImageView resource on RemoteView Android

I'm trying yo make a simple widget with clickable image that will change when its clicked.
I don't understand why it doesn't work
public class AppWidget extends AppWidgetProvider {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction()==null) {
context.startService(new Intent(context,
ToggleService.class));
} else {
super.onReceive(context, intent);
}
}
#Override
public void onUpdate(Context context, AppWidgetManager
appWidgetManager, int[] appWidgetIds) {
context.startService(new Intent(context,
ToggleService.class));
}
public static class ToggleService extends IntentService {
public ToggleService() {
super("AppWidget$ToggleService");
}
#Override
protected void onHandleIntent(Intent intent) {
ComponentName me=new ComponentName(this, AppWidget.class);
AppWidgetManager mgr=AppWidgetManager.getInstance(this);
mgr.updateAppWidget(me, buildUpdate(this));
}
private RemoteViews buildUpdate(Context context) {
RemoteViews updateViews=new
RemoteViews(context.getPackageName(),R.layout.widget);
int a = 1;
if(a ==
1) {
updateViews.setImageViewResource(R.id.phoneState,
R.drawable.dual_off);
} else {
updateViews.setImageViewResource(R.id.phoneState,
R.drawable.dual_on);
}
Intent i=new Intent(this, AppWidget.class);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, i,0);
updateViews.setOnClickPendingIntent(R.id.phoneState,pi);
return updateViews;
}
}
}
I have tried all sort of things in for loop but it just won't change image.
I have done this from a book about android development, am new to java and android.
You would to update your widget by AppWidgetManager, after changing remoteview's source.In this snippet code I try to change layout of widget that it's AppWidgetProvider name is DictionWidgetProvider :
private void hideWidgetInstances() {
hideViews = new RemoteViews(App.getContext().getPackageName(),
R.layout.hide);
AppWidgetManager mManager = AppWidgetManager.getInstance(App
.getContext());
ComponentName cn = new ComponentName(App.getContext(),
DictionWidgetProvider.class);
mManager.updateAppWidget(cn, hideViews);
}
Here App is a class that extends Application.You can use Application Context to reach ComponentName.

How do I start an Activity when my Widget is clicked?

I have this widget that toggles sound on off but instead of that I want to call another activity (MYxz.class) please tell me what should I change here...
public class AppWidget extends AppWidgetProvider {
#Override
public void onReceive(Context ctxt, Intent intent)
{
if(intent.getAction()==null)
{
ctxt.startService(new Intent(ctxt,ToggleService.class));
}
else
{
super.onReceive(ctxt, intent);
}
}
#Override
public void onUpdate(Context context,AppWidgetManager appWidgetManager, int [] appWidgetIds)
{
context.startService(new Intent(context,ToggleService.class));
//RemoteViews buildUpdate(context);
}
public static class ToggleService extends IntentService
{
public ToggleService() {
super("AppWidget$ToggleService");
}
#Override
protected void onHandleIntent(Intent intent)
{
ComponentName me = new ComponentName(this,AppWidget.class);
AppWidgetManager mgr= AppWidgetManager.getInstance(this);
mgr.updateAppWidget(me,buildUpdate(this));
}
private RemoteViews buildUpdate(Context context)
{
RemoteViews updateViews=new RemoteViews(context.getPackageName(),R.layout.widget);
AudioManager audioManager=(AudioManager)context.getSystemService(Activity.AUDIO_SERVICE);
if(audioManager.getRingerMode()==AudioManager.RINGER_MODE_SILENT)
{
updateViews.setImageViewResource(R.id.phoneState,R.drawable.silent);
audioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
}
else {
updateViews.setImageViewResource(R.id.phoneState,R.drawable.phone123);
audioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
}
Intent i=new Intent(this, AppWidget.class);
PendingIntent pi= PendingIntent.getBroadcast(context,0, i,0);
updateViews.setOnClickPendingIntent(R.id.phoneState,pi);
return updateViews;
}
}
}
Yes possible see example:
Upadte your manifest.xml
<receiver android:name=".AppWidget"
android:label="Caller"
android:icon="#drawable/ic_launcher" >
<intent-filter >
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
<action android:name="com.app.example.MyWidget.ACTION_WIDGET_CLICK_RECEIVER"/>
</intent-filter>
<meta-data
android:name="android.appwidget.provider"
android:resource="#xml/widget_provider"
/>
</receiver>
<service android:name=".AppWidget$ToggleService" />
and Update your AppWidgetProvider:
public class MyWidget extends AppWidgetProvider {
public static String ACTION_WIDGET_CLICK_RECEIVER = "ActionReceiverWidget";
public static int appid[];
public static RemoteViews rview;
#Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds){
updateWidgetState(context, "");
}
#Override
public void onReceive(Context paramContext, Intent paramIntent)
{
String str = paramIntent.getAction();
if (paramIntent.getAction().equals(ACTION_WIDGET_CLICK_RECEIVER)) {
updateWidgetState(paramContext, str);
}
else
{
if ("android.appwidget.action.APPWIDGET_DELETED".equals(str))
{
int i = paramIntent.getExtras().getInt("appWidgetId", 0);
if (i == 0)
{
}
else
{
int[] arrayOfInt = new int[1];
arrayOfInt[0] = i;
onDeleted(paramContext, arrayOfInt);
}
}
super.onReceive(paramContext, paramIntent);
}
}
static void updateWidgetState(Context paramContext, String paramString)
{
RemoteViews localRemoteViews = buildUpdate(paramContext, paramString);
ComponentName localComponentName = new ComponentName(paramContext, MyWidget.class);
AppWidgetManager.getInstance(paramContext).updateAppWidget(localComponentName, localRemoteViews);
}
private static RemoteViews buildUpdate(Context paramContext, String paramString)
{
// Toast.makeText(paramContext, "buildUpdate() ::"+paramString, Toast.LENGTH_SHORT).show();
rview = new RemoteViews(paramContext.getPackageName(), R.layout.widget_layout);
Intent active = new Intent(paramContext, MyWidget.class);
active.setAction(ACTION_WIDGET_RECEIVER);
PendingIntent configPendingIntent = PendingIntent.getActivity(paramContext, 0, active, 0);
// upadte this R.id.buttonus1 with your layout or image id on which click you want to start Activity
Intent configIntent = new Intent(paramContext, Caller2.class);
configIntent.setAction((ACTION_WIDGET_CLICK_RECEIVER);
PendingIntent configPendingIntent = PendingIntent.getActivity(paramContext, 0, configIntent, 0);
rview.setOnClickPendingIntent(R.id.Phonestatexx, configPendingIntent);
if(parmString.equals(ACTION_WIDGET_CLICK_RECEIVER))
{
//open Activity here..
//your code for update and what you want on button click
//
}
return rview;
}
#Override
public void onEnabled(Context context){
super.onEnabled(context);
// Toast.makeText(context, "onEnabled() ", Toast.LENGTH_SHORT).show();
}
// Called each time an instance of the App Widget is removed from the host
#Override
public void onDeleted(Context context, int [] appWidgetId){
super.onDeleted(context, appWidgetId);
// Toast.makeText(context, "onDeleted() ", Toast.LENGTH_SHORT).show();
}
// Called when last instance of App Widget is deleted from the App Widget host.
#Override
public void onDisabled(Context context) {
super.onDisabled(context);
// Toast.makeText(context, "onDisabled() ", Toast.LENGTH_SHORT).show();
}
}
Instead of:
Intent active = new Intent(paramContext, AppWidget.class);
You use:
Intent active = new Intent(paramContext, YOURCLASS.class);
before you create the pending intent, #imran khan helped me but there are some tweaks you should do 2...this should fire up the Activity you need.
With using pendingIntents you can call an intent (to your activity or sth else) when a widget item clicked. this may help:
http://www.vogella.de/articles/AndroidWidgets/article.html

Widget double click

I have a widget (AppWidgetProvider) and i want to know if there is a way to support multiple clicks.Example:
1)If is the first click on the widget, then the ImageButton of the widget changes (for example, changes the color).
2)If is the second time, then open an Activity.
-- There is some way to handle click events inside AppWidgetProvider?
My code:
public class MyWidgetProvider extends AppWidgetProvider
{
#Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
final int N = appWidgetIds.length;
for (int i=0; i<N; i++) {
int appWidgetId = appWidgetIds[i];
Intent intent = new Intent(context, MyActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.control_widget);
views.setOnClickPendingIntent(R.id.asdf, pendingIntent);
appWidgetManager.updateAppWidget(appWidgetId, views);
}
}
}
My widget is working fine. When i click the ImageButton(R.id.asdf), it goes to the activity MyActivity.
Id like to know how can i handle click events on my widget to make a different action (example: change the color of the ImageButton) instead of go to some activity. Is there some other way to some click handle besides setOnClickPendingIntent()?
Maybe this could help. It works for me:
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);
}
}
I did it this way:
1)If is the first click on the widget, then the ImageButton of the widget changes
2)If is the second time, then open an Activity and return to the inicial ImageButton state.
Im handling click events with setOnClickPendingIntent:
private int[] RESOURCES = {R.drawable.button1,R.drawable.button2};
#Override
public void onUpdate(Context context, AppWidgetManager mgr, int[] appWidgetIds) {
ComponentName me = new ComponentName(context, MyWidgetProvider.class);
RemoteViews remoteViews = new RemoteViews(context.getPackageName(),R.layout.my_widget);
Intent widgetIntent = new Intent(context, MyWidgetProvider.class);
Intent myIntent= new Intent(context, MyOtherActivity.class);
widgetIntent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
widgetIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, appWidgetIds);
PendingIntent pendingIntent;
if(clicks == 0)
{
clicks = 1;
remoteViews.setImageViewResource(R.id.my_image_button, RESOURCES[0]);
pendingIntent = PendingIntent.getBroadcast(context, 0, widgetIntent, PendingIntent.FLAG_UPDATE_CURRENT);
}
else if(clicks == 1)
{
clicks = 2;
remoteViews.setImageViewResource(R.id.my_image_button, RESOURCES[1]);
pendingIntent = PendingIntent.getActivity(context, 0, myIntent,0);
}
else //clicks == 2
{
clicks = 0;
remoteViews.setImageViewResource(R.id.my_image_button, RESOURCES[0]);
pendingIntent = PendingIntent.getBroadcast(context, 0, widgetIntent, PendingIntent.FLAG_UPDATE_CURRENT);
}
remoteViews.setOnClickPendingIntent(R.id.my_image_button, pendingIntent);
mgr.updateAppWidget(me, remoteViews);
}
#Override
public void onEnabled(Context context) {
clicks = 0;
super.onEnabled(context);
}
Unlike Button and its subclasses, AppWidget doesn't have the concept of an onClickListener. AppWidgets have to provide a PendingIntent for the application that hosts them to fire when the widget is clicked. If you wanted to track multiple clicks, you would need to have a receiver that filters on an intent specific to your widget and keeps track of how many times it has received it.
Slightly-less-relevant: You might reconsider your behavior model. Android is a one-click-to-take-action environment that doesn't have the same "click-once-to-select" concept like you'd find in, say, Windows. By emulating that behavior, your widget won't behave like all of the other UI elements and may cause confusion. Additionally, if there are two of your widgets on the screen and the user taps one and then the other, both will appear "selected," which probably isn't what you want.
Why not just count the clicks yourself?
private class MyAwesomeClickListener implements OnClickListener {
private int clicks = 0;
#Override
public void onClick(View v) {
++clicks;
//do some cool stuff
}
}
Don't count it in a listener (it's ridiculous, you don't know when your widget will be recycled from the memory and you will lose the value of int clicks)
Persist the number of clicks (add +1 each time it is clicked, restart to 0 when you reach the end of the click "cycle", the end of different click behaviors).
You could persist them in a database, with serialization, or with the shared preferences (I guess the preferences are the easiest way)
This is what I'm doing. Works beautifully =]
public class MyWidgetProvider extends AppWidgetProvider {
//Length of allowed time in between clicks in milliseconds
private static final long DOUBLE_CLICK_WINDOW = 400;
private static volatile long firstClickTimeReference;
#Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
final int N = appWidgetIds.length;
for (int i=0; i<N; i++) {
int appWidgetId = appWidgetIds[i];
long currentSystemTime = System.currentTimeMillis();
if(currentSystemTime - firstClickTimeReference <= DOUBLE_CLICK_WINDOW) {
//double click happened in less than 400 miliseconds
//so let's start our activity
Intent intent = new Intent(context, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity( intent );
} else {
firstClickTimeReference = currentSystemTime;
RemoteViews remoteViews = new RemoteViews(context.getPackageName(),
R.layout.control_widget);
Intent intent = new Intent(context, WidgetProvider.class);
intent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, appWidgetIds);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context,
0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
remoteViews.setOnClickPendingIntent(R.id.actionButton, pendingIntent);
appWidgetManager.updateAppWidget(widgetId, remoteViews);
}
}
}
}
The solution by almisoft provides a double-click feel rather than simply successive clicks. And it works. Unfortunately you also get a lint message telling you that the 'handler class should be static or leaks might occur'. The solution is to use a weak reference and static handler - a generic version is here. Converting almisoft's code gives:
public class WidgetProvider extends AppWidgetProvider {
private static final int DOUBLE_CLICK_DELAY = 500;
private static Context mContext;
private static int mClickCount;
private static class MyHandler extends Handler {
//Using a weak reference means you won't prevent garbage collection
private final WeakReference<WidgetProvider> myClassWeakReference;
public MyHandler(WidgetProvider myClassInstance) {
myClassWeakReference = new WeakReference<WidgetProvider>(myClassInstance);
}
#Override
public void handleMessage(Message msg) {
WidgetProvider myWidget = myClassWeakReference.get();
if (myWidget != null) {
//...do work here as in almisoft original...
int clickCount = mContext.getSharedPreferences("widget", Context.MODE_PRIVATE).getInt("clicks", 0);
if (clickCount > 1) {
Toast.makeText(mContext, "doubleClick", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(mContext, "singleClick", Toast.LENGTH_SHORT).show();
}
mContext.getSharedPreferences("widget", Context.MODE_PRIVATE).edit().putInt("clicks", 0).commit();
}
}
}
#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) {
mContext=context;
mIntent=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 MyHandler(this);
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);
}
}

Categories

Resources