[SOLVED] Lockscreen Widget forgets onUpdate init code after reopening the lockscreen - Java for Android App Development

I made a simple widget, which has a few buttons. In order to make those buttons work, I use RemoteViews.setOnClickPendingIntent in the onUpdate method of the AppWidgetProvider. Works fine, as long as I place the widget only on the homescreen. But when using the widget on the lockscreen, I have the following problem:
Placing the widget on the lockscreen and immediately clicking the buttons works perfectly. But after closing the lockscreen and reopening it, the buttons don't work anymore. It seems like the widget had "forgotten" everything from the init stuff in the onUpdate method.
So, does somebody know how to fix this?
Some code snippets:
Code:
public class WidgetProvider extends AppWidgetProvider {
private static final String BUTTON_ALL_OFF = "buttonAllOff";
private RemoteViews remoteViews;
private ComponentName watchWidget;
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
super.onUpdate(context, appWidgetManager, appWidgetIds);
remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget_layout);
watchWidget = new ComponentName(context, WidgetProvider.class);
remoteViews.setOnClickPendingIntent(R.id.buttonAllOff, getPendingSelfIntent(context, BUTTON_ALL_OFF));
appWidgetManager.updateAppWidget(watchWidget, remoteViews);
}
@Override
public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);
String action = intent.getAction();
remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget_layout);
watchWidget = new ComponentName(context, WidgetProvider.class);
if (BUTTON_ALL_OFF.equals(action)) {
Log.d("test", "clicked");
//do fancy stuff
}
}
protected PendingIntent getPendingSelfIntent(Context context, String action) {
Intent intent = new Intent(context, getClass());
intent.setAction(action);
return PendingIntent.getBroadcast(context, 0, intent, 0);
}
}
Code:
<?xml version="1.0" encoding="utf-8"?>
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
android:initialLayout="@layout/widget_layout"
android:minHeight="700dp"
android:minWidth="300dp"
android:resizeMode="vertical"
android:updatePeriodMillis="0"
android:widgetCategory="home_screen|keyguard" >
</appwidget-provider>

Fixed it by adding the clicklistener also in the onReceive method

Related

widget SMS for android

Hello,
I'm trying to write code of a widget sms for android. But I have a problem of cursor, after lot of test on compiling I dircoverd that
Code:
Cursor c = context.getContentResolver().query(Uri.parse("content://sms/"), null, null ,null,null);
make an error and I don't no why. If somebody knows how use a cursor or have a better idea to view sms without cursor, I woold like share it with him!
thank's
try something like this
Code:
Uri uriSms = Uri.parse("content://sms/inbox");
Cursor c = getContentResolver().query(uriSms, null,null,null,null);
Thank's to you Draffodx, I such begin my widget, now it can put on screen the sms I want... but I can't change of SMS with th button I've created. I don't understand how make a button with the widget because it need to be an Activity for a button and I've made an AppWidget...
I trying to do like this:
Code:
public class MySMSwidget extends AppWidgetProvider implements View.OnClickListener {
private Button Bnext;
private int sms_id=0;
public class MyActivity extends Activity {
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.widget_layout);
final Button button = (Button) findViewById(R.id.next);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (v==Bnext){sms_id=sms_id+1;}
}
});
}
}.... and the rest of the code
But when I click the button, nothing happend.
hey, my idea seems to be a bad idea so I try this way:
Code:
public class MySMSwidget extends AppWidgetProvider {
private int sms_id=0;
public void onReceive (Context context, Intent intent){
if (Intent.ACTION_ATTACH_DATA.equals(intent.getAction()))
{
Bundle extra = intent.getExtras();
sms_id = extra.getInt("Data");
}
}
public void onUpdate(Context context, AppWidgetManager
appWidgetManager, int[] appWidgetIds) {
Cursor c = context.getContentResolver().query(Uri.parse("content://
sms/inbox"), null, null ,null,null);
String body = null;
String number = null;
String date = null;
c.moveToPosition(sms_id);
body = c.getString(c.getColumnIndexOrThrow("body")).toString();
number =
c.getString(c.getColumnIndexOrThrow("address")).toString();
date = c.getString(c.getColumnIndexOrThrow("date")).toString();
c.close();
RemoteViews updateViews = new RemoteViews(context.getPackageName(),
R.layout.widget_layout);
updateViews.setTextColor(R.id.text, 0xFF000000);
updateViews.setTextViewText(R.id.text,date+'\n'+number+'\n'+body);
ComponentName thisWidget = new ComponentName(context,
MySMSwidget.class);
appWidgetManager.updateAppWidget(thisWidget, updateViews);
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_ATTACH_DATA);
RemoteViews views = new RemoteViews(context.getPackageName(),
R.layout.widget_layout);
views.setOnClickPendingIntent(R.id.next, changeData(context));
}
private PendingIntent changeData(Context context) {
Intent Next = new Intent();
Next.putExtra("Data", sms_id+1);
Next.setAction(Intent.ACTION_ATTACH_DATA);
return(PendingIntent.getBroadcast(context,
0, Next, PendingIntent.FLAG_UPDATE_CURRENT));
}
}
my code isn't terminated.
I hope there will be someone to help to correct it.
Just want to display next SMS.
Please help.

Gmail Text Cloud Widget

ive been enamored by some of the more simple text based widgets as of late (like simplistic text and clockr) and decided to try to make a widget based on that design for gmail. it will display who the email is from in a text cloud where the most recent email is the largest with each subsequent email getting smaller. if the email is unread it will be bold, if not then it will be regular text.
my background is in making java apps for the command line and of a more linear layout. so i am learning android dev as i go. because i am learning as i go i am starting at the most basic and moving on. i have a widget with a text box that displays '0'. (yay! i know impressive). now i want to make the text increment by 1 every 1 second. (yes not very useful, but very useful for learning.) i want to do this with an AlarmManager. does the AlarmManager have to be in a service, or an adjacent activity, or could there be a static AlarmManager in my AppWidgetProvider class? i found some examples but they are all pretty complex. i want to start super simple and move towards advanced.
after that then i will do the same increment except each number will be added as a new textbox and the previous will decrease in size. and so on and so on.
any help would be greatly appreciated.
-Tyler
so i understand that a Handler is better for these small tics of times but doing this project is a learning excersise. let me show you what i have so far.
AndroidManifest.xml
Code:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.tsb.gmailinboxtextcloud"
android:versionCode="1"
android:versionName="1.0">
<application android:label="GmailInboxTextCloud" android:icon="@drawable/gitc_icon">
<!-- Broadcast Receiver that will process AppWidget updates -->
<receiver android:name=".GITextCloud" android:label="@string/app_name">
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
</intent-filter>
<!--
<intent-filter>
<action android:name="INCREMENT_COUNT_UPDATE" />
<action android:name="RESET_COUNT_UPDATE" />
<action android:name="PAUSE_COUNT_UPDATE"/>
</intent-filter>
-->
<meta-data android:name="android.appwidget.provider" android:resource="@xml/gitc_widget"/>
</receiver>
</application>
<service android:enabled="true" android:name=".AlarmService" />
</manifest>
my widget class
GITextCloud.java
Code:
package com.tsb.gmailinboxtextcloud;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.widget.RemoteViews;
import android.widget.Toast;
public class GITextCloud extends AppWidgetProvider {
private int count = 0;
@Override
public void onEnabled(Context context) {
//super.onEnabled(context);
count = 0;
context.startService(new Intent(context, AlarmService.class));
Toast.makeText(context, "onEnabled() finished", Toast.LENGTH_LONG).show();
}
@Override
public void onDisabled(Context context) {
//super.onDisabled(context);
count = 0;
context.stopService(new Intent(context, AlarmService.class));
Toast.makeText(context, "onDisabled() finished", Toast.LENGTH_LONG).show();
}
@Override
public void onReceive(Context context, Intent intent) {
//super.onReceive(context, intent);
RemoteViews rv = new RemoteViews(context.getPackageName(), R.layout.main);
rv.setTextViewText(R.id.widget_textview, "[" + count + "]");
AppWidgetManager manager = AppWidgetManager.getInstance(context);
ComponentName cName = new ComponentName(context, GITextCloud.class);
manager.updateAppWidget(cName, rv);
count++;
}
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
}
}
my service that runs an AlarmManager
AlarmService.java
Code:
package com.tsb.gmailinboxtextcloud;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;
/**
* Created by IntelliJ IDEA.
* User: Tyler
* Date: 4/16/11
* Time: 6:34 PM
*/
public class AlarmService extends Service {
private AlarmManager am;
private PendingIntent pendingIntent;
// public static String INCREMENT_COUNT_UPDATE = "INCREMENT_COUNT_UPDATE";
// public static String RESET_COUNT_UPDATE = "RESET_COUNT_UPDATE";
// public static String PAUSE_COUNT_UPDATE = "PAUSE_COUNT_UPDATE";
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show();
am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
}
@Override
public void onDestroy() {
Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
am.cancel(pendingIntent);
}
@Override
public void onStart(Intent intent, int startid) {
Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
setRepeatingAlarm(GITextCloud.class);
}
public void setOneTimeAlarm(java.lang.Class<?> cls) {
Intent intent = new Intent(this, cls);
pendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + (5 * 1000), pendingIntent);
}
public void setRepeatingAlarm(java.lang.Class<?> cls) {
Intent intent = new Intent(this, cls);
pendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), (5 * 1000), pendingIntent);
}
}
what ends up happening is that my widget just shows [0] in white and 60sp big. never changes. and my toasts in the service never show up on the screen. am i starting the service wrong?
Is this just a stupid question or does no one know the answer? Cause if no one knows then nvm, wrong place to ask...
Its from my damn phone!!!
I haven't messed too much with app widgets, but don't you have to set some sort of refresh time in your metadata?
http://developer.android.com/guide/topics/appwidgets/index.html
Gene Poole said:
I haven't messed too much with app widgets, but don't you have to set some sort of refresh time in your metadata?
http://developer.android.com/guide/topics/appwidgets/index.html
Click to expand...
Click to collapse
yep, that determines how often the ACTION_APPWIDGET_UPDATE intent gets sent.
my gitc_widget.xml
Code:
<?xml version="1.0" encoding="utf-8"?>
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
android:minWidth="146dip"
android:minHeight="72dip"
android:updatePeriodMillis="1000"
android:initialLayout="@layout/main">
</appwidget-provider>
buuut. after android 1.6 or maybe 1.5 that android:updatePeriodMillis tag defaults to 30minutes. which is why an AlarmManager must be used for anything less than 30min updates. and since i dont want to wait 30mins to know if my code works i need my service to start.
i have determined that my service never starts. it isnt shown in the running services on my android phone and the toasts from it never show. anyone know why the service isnt started?
As mentioned earlier, I don't know a lot about appwidgets, but they are incredibly difficult to debug and I've had to reboot the phone at times to get past bugs in my code, so don't be so sure that your service isn't running. First, I don't think AppServices show up in the "running services" tab, and second, I don't think toasts from a non-activity show up on the screen. I could be wrong about this, so don't take it as gospel. Try using Log() instead of Toast for debugging.
Also, I don't see anything in your code that sends an update to the appwidget. I think something in your service should eventually call GITextCloud.updateAppWidget().
Thanks for working with me. In my AlarmService class in the onStarted method i call the setRepeating() method that gets passed a class with wich it makes an intent that the AlarmManager should use to trigger the onRecieve() method in my GITextCloud class. I will look into the log(), thats a good idea. And i will be trying to setAction() on that intent and then specifically catch it in the onRecieve() method
Thanks for giving me something to think about
Its from my damn phone!!!
i made some edits and ran into a problem where my intent was caught be onReive() but the local variable called count never incremented... this is crazy! a block of code that would execute whenever a particular intent was recieved never did what i wanted:
count++;
refreshWidgets();
Toast.makeText(.... some indication this was done ...);
the toast was always displayed but the count never incremented. i thought the refreshWidgets method was bunk so i manually set the count in the method... everything was good... then i make a toast after the count++ to display count. count never incremented. well after messing around i found that i had count as a
private int count
i changed it to a
private static int count
and it worked! weird...
this is my final code that makes a number on a widget increment every couple of seconds. note: setting a repeating alarm with the AlarmManager for a small amount of time did not work. i had to make a nested one time alarm that kept rearming itself. and i got rid of the service cause some of the debuging tools in cm7 said it never started. cross that bridge when i get there....
Code:
package com.tsb.gmailinboxtextcloud;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.widget.RemoteViews;
import android.widget.Toast;
public class GITextCloud extends AppWidgetProvider {
private static int count = 0;
private static int widgetCount = 0;
public static final String INCREMENT_COUNT_UPDATE = "INCREMENT_COUNT_UPDATE";
@Override
public void onEnabled(Context context) {
super.onEnabled(context);
count = 0;
setOneTimeAlarm(this.getClass(), context);
}
@Override
public void onDisabled(Context context) {
super.onDisabled(context);
}
@Override
public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);
if (intent.getAction().equals("android.appwidget.action.APPWIDGET_ENABLED")) {
} else if (intent.getAction().equals("android.appwidget.action.APPWIDGET_DISABLED")) {
} else if (intent.getAction().equals(INCREMENT_COUNT_UPDATE)) {
count++;
refreshViews(context);
Toast.makeText(context, "widget #" + widgetCount, Toast.LENGTH_SHORT).show();
if (widgetCount != 0) {
setOneTimeAlarm(this.getClass(), context);
}
} else {
//Toast.makeText(context, "count = " + count + " | " + intent.getAction(), Toast.LENGTH_LONG).show();
}
}
/** Called when the activity is first created. */
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
//super.onUpdate(context, appWidgetManager, appWidgetIds);
}
private void refreshViews(Context context) {
RemoteViews rv = new RemoteViews(context.getPackageName(), R.layout.main);
rv.setTextViewText(R.id.widget_textview, "" + count);
AppWidgetManager manager = AppWidgetManager.getInstance(context);
ComponentName cName = new ComponentName(context, GITextCloud.class);
widgetCount = manager.getAppWidgetIds(cName).length;
manager.updateAppWidget(cName, rv);
}
private void setOneTimeAlarm(java.lang.Class<?> cls, Context context) {
AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, cls);
intent.setAction(INCREMENT_COUNT_UPDATE);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_ONE_SHOT);
am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + (3 * 1000), pendingIntent);
}
}

[Q] Handling ACTION_SCREEN in a widget

Hi,
I'm doing a widget that needs to be update on screen_on or on
user_present. As I'm not hable to register a BroadcastReceiver inside
the widget I'm doing it in a Service that is triggered by the widget
like this:
Widget.java:
Code:
@Override
public void onEnabled(Context context) {
super.onEnabled(context);
context.startService(new Intent(context,
WidgetService.class).setAction(WidgetService.ACTION_WIDGET_START));
}
WidgetService.java:
Code:
@Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
String action = intent.getAction();
Log.d(LOG_APP,"WidgetService onStart: "+action);
if (ACTION_WIDGET_STOP.equals(action)) {
this.unregisterReceiver(mReceiver);
stopSelf();
return;
} else if (ACTION_WIDGET_START.equals(action)) {
// register receiver that handles screen on and screen off logic
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
this.registerReceiver(mReceiver, filter);
return;
}
The problem is that when I try to register the receiver I get the
error that the service has leaked IntentReceiver because it was
already registered. Ive checked and no duplicate registration was done
in my code.
Do you have any idea what I'm overlooking?
Thanks,
PMD

[Q][SOLVED] PreferenceActivity as AppWidget Config

I have been using a hand built ListActivity as my AppWidget config Activity but to be honest it looks ****ty and doesnt fit in with the rest of the app. So i wanted to transition over to a PreferenceActivity. i made a stub of a PreferenceActivity that launches the layout just fine when it is the main activity. but when i try to change from my ListActivity to my PreferenceAcitivity i get no launching of PreferenceActivity when i launch my widget. all i get is my widget.
i did a refactoring of my xml files to change the instances of my ListActivity (GITextConfig) to my PreferenceActivity (GITextPreferences).
how can i use a PreferenceActivity as my config?
do i need to have a dummy Activity be the config with a button to launch the PreferenceActivity? cause that works just fine. its lame and shouldnt be that way... nvm that does not work... i just cant get a prefs activity to run from an appwidget
anyone? this is quite annoying... i know it can be done as other widgets like gmail unread count does this. at least it appears to have a preferenceactivity as the configuration
got it to work. i dont know what i was doing before but i think i had a little too much of a stub for it to work. after i implemented the appwidget id verification and created my PreferenceManger and overode the onBackPressed() method it seems to work.... happy and confused.
Code:
public class GITextPreferences extends PreferenceActivity {
private int mAppWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
PreferenceManager localPrefs = getPreferenceManager();
localPrefs.setSharedPreferencesName("GITC_Prefs");
addPreferencesFromResource(R.xml.gitc_preferences);
// Find the widget id from the intent.
Intent intent = getIntent();
Bundle extras = intent.getExtras();
if (extras != null) {
mAppWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
}
// If they gave us an intent without the widget id, just bail.
if (mAppWidgetId == AppWidgetManager.INVALID_APPWIDGET_ID) {
finish();
}
}
@Override
public void onBackPressed() {
// Make sure we pass back the original appWidgetId
Intent resultValue = new Intent();
resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mAppWidgetId);
setResult(RESULT_OK, resultValue);
finish();
}
}

[Q] Dialog out of Activity

Hello app developers!
I have got serious problem. Every time I call alertdialogs or other dialogs I see them only in activity. But my app needs to show this dialog when user works on phone, that's why it must be shown out of activity. Any ideas?
DoR2 said:
Hello app developers!
I have got serious problem. Every time I call alertdialogs or other dialogs I see them only in activity. But my app needs to show this dialog when user works on phone, that's why it must be shown out of activity. Any ideas?
Click to expand...
Click to collapse
You cannot do this. There is simply no feature for that. I have had that problem, too.
Use a Notification or a Toast message.
There is a work-around for this. If you run a service, you can technically launch an activity that can resemble this.
I have an app that uses a broadcast receiver to listen for the events I want to alert my user to. I created a custom layout for my alert dialog and then when the event happens, my broadcast receiver calls the activity.
zalez said:
There is a work-around for this. If you run a service, you can technically launch an activity that can resemble this.
I have an app that uses a broadcast receiver to listen for the events I want to alert my user to. I created a custom layout for my alert dialog and then when the event happens, my broadcast receiver calls the activity.
Click to expand...
Click to collapse
Yes, great idea. Launch a transparent Activity and start a dialog. Set an onDismissListener and close the app when the dialog is closed.
nikwen said:
Yes, great idea. Launch a transparent Activity and start a dialog. Set an onDismissListener and close the app when the dialog is closed.
Click to expand...
Click to collapse
If I start a transparent activity user can't see that it was started as I understand. Can you give code for broadcast receiver maybe I misunderstand something
The broadcast receiver is just the mechanism I use to launch the activity. It is a mere intent that I start from it. Below is the class I use for my alertdialog. You won't be able to cut and paste because I also created my own class to dismiss the activity.
Code:
public class SilentDialog extends TimedActivity implements OnTouchListener{
Intent intent;
[user=439709]@override[/user]
public void onCreate(Bundle savedInstanceState) {
//Remove title bar
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
//Remove notification bar
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
super.onCreate(savedInstanceState);
showAlert();
}
[user=439709]@override[/user]
protected void onDestroy()
{
//this is very important here ;)
super.onDestroy();
}
public boolean onTouch(View v, MotionEvent event)
{
final int actionPerformed = event.getAction();
//reset idle timer
// put this here so that the touching of empty space is captured too
// it seems that LinearLayout doesn't trigger a MotionEvent.ACTION_UP or MotionEvent.ACTION_MOVE
if (actionPerformed == MotionEvent.ACTION_DOWN)
{
super.onTouch();
}
return false;//do not consume event!
}
public void showAlert(){
//would you like it to expire?
AlertDialog.Builder builder;
final AlertDialog alertDialog;
Context mContext = SilentDialog.this;
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.pop1,
(ViewGroup) findViewById(R.id.layout_root));
NumberPicker spin = (NumberPicker) layout.findViewById(R.id.SpinRate);
spin.setVisibility(8);
TextView rate = (TextView) layout.findViewById(R.id.RateTitle);
rate.setVisibility(8);
TextView text = (TextView) layout.findViewById(R.id.txtAlertDiag);
text.setText("ButlerSMS has detected the ringer mode has changed to silent. " +
"\n\n Would you like ButlerSMS to turn on?");
final NumberPicker picker = (NumberPicker) layout.findViewById(R.id.SpinRate);
picker.setValue(60);
builder = new AlertDialog.Builder(mContext);
builder.setView(layout);
builder.setTitle("ButlerSMS - Silent Mode");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
intent = new Intent(getBaseContext(), ButlerWidget.class);
intent.setAction("StartSMS");
intent.putExtra("msg","Normal");
sendBroadcast(intent);
finish();
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Canceled.
finish();
}
});
alertDialog = builder.create();
alertDialog.show();
final Timer t = new Timer();
t.schedule(new TimerTask() {
public void run() {
alertDialog.dismiss(); // when the task is active then close the dialog
t.cancel(); // also just top the timer thread, otherwise, you may receive a crash report
finish();
}
}, 19000);
}
}
zalez said:
The broadcast receiver is just the mechanism I use to launch the activity. It is a mere intent that I start from it. Below is the class I use for my alertdialog. You won't be able to cut and paste because I also created my own class to dismiss the activity.
Code:
public class SilentDialog extends TimedActivity implements OnTouchListener{
Intent intent;
[user=439709]@override[/user]
public void onCreate(Bundle savedInstanceState) {
//Remove title bar
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
//Remove notification bar
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
super.onCreate(savedInstanceState);
showAlert();
}
[user=439709]@override[/user]
protected void onDestroy()
{
//this is very important here ;)
super.onDestroy();
}
public boolean onTouch(View v, MotionEvent event)
{
final int actionPerformed = event.getAction();
//reset idle timer
// put this here so that the touching of empty space is captured too
// it seems that LinearLayout doesn't trigger a MotionEvent.ACTION_UP or MotionEvent.ACTION_MOVE
if (actionPerformed == MotionEvent.ACTION_DOWN)
{
super.onTouch();
}
return false;//do not consume event!
}
public void showAlert(){
//would you like it to expire?
AlertDialog.Builder builder;
final AlertDialog alertDialog;
Context mContext = SilentDialog.this;
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.pop1,
(ViewGroup) findViewById(R.id.layout_root));
NumberPicker spin = (NumberPicker) layout.findViewById(R.id.SpinRate);
spin.setVisibility(8);
TextView rate = (TextView) layout.findViewById(R.id.RateTitle);
rate.setVisibility(8);
TextView text = (TextView) layout.findViewById(R.id.txtAlertDiag);
text.setText("ButlerSMS has detected the ringer mode has changed to silent. " +
"\n\n Would you like ButlerSMS to turn on?");
final NumberPicker picker = (NumberPicker) layout.findViewById(R.id.SpinRate);
picker.setValue(60);
builder = new AlertDialog.Builder(mContext);
builder.setView(layout);
builder.setTitle("ButlerSMS - Silent Mode");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
intent = new Intent(getBaseContext(), ButlerWidget.class);
intent.setAction("StartSMS");
intent.putExtra("msg","Normal");
sendBroadcast(intent);
finish();
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Canceled.
finish();
}
});
alertDialog = builder.create();
alertDialog.show();
final Timer t = new Timer();
t.schedule(new TimerTask() {
public void run() {
alertDialog.dismiss(); // when the task is active then close the dialog
t.cancel(); // also just top the timer thread, otherwise, you may receive a crash report
finish();
}
}, 19000);
}
}
Click to expand...
Click to collapse
I understood everything except the way how app switch between position before signal came and required activity with alert dialog in it. As I see this code initialize activity and alert dialog but don't contain switching that I need
Are you asking how I call the dialog? If so, a simple intent from a broadcast receiver.
Code:
Intent i = new Intent(context, SilentDialog.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
I would use the AlertDialog.Builder class for compatibility.
Why not use a notification, I think that is more elegant.
Code:
public class InstalledReceiver extends BroadcastReceiver {
private NotificationManager mNotificationManager ;
[user=439709]@override[/user]
public void onReceive(Context context, Intent intent) {
if (BaseActivity.DEBUG) System.out.println("Received Broadcast");
Boolean update = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
mNotificationManager = (NotificationManager) context.getSystemService("notification");
SharedPreferences getPrefs = PreferenceManager.getDefaultSharedPreferences(context);
Boolean disabledNotifications = getPrefs.getBoolean("disableNotifications", false);
if (!disabledNotifications && !update) makeNotification(context);
}
private void makeNotification(Context context) {
CharSequence label = context.getString(R.string.labelNotify);
CharSequence text = context.getString(R.string.textNotify);
CharSequence full = context.getString(R.string.fullNotify);
final Notification notification = new Notification(R.drawable.ic_launcher,text,System.currentTimeMillis());
notification.setLatestEventInfo(context,label,full,null);
notification.defaults = Notification.DEFAULT_ALL;
mNotificationManager.notify( 0, notification);
}
}
Taptalked u see .. əəs n pəʞlɐʇdɐʇ
Zatta said:
Why not use a notification, I think that is more elegant.
Code:
public class InstalledReceiver extends BroadcastReceiver {
private NotificationManager mNotificationManager ;
[user=439709]@override[/user]
public void onReceive(Context context, Intent intent) {
if (BaseActivity.DEBUG) System.out.println("Received Broadcast");
Boolean update = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
mNotificationManager = (NotificationManager) context.getSystemService("notification");
SharedPreferences getPrefs = PreferenceManager.getDefaultSharedPreferences(context);
Boolean disabledNotifications = getPrefs.getBoolean("disableNotifications", false);
if (!disabledNotifications && !update) makeNotification(context);
}
private void makeNotification(Context context) {
CharSequence label = context.getString(R.string.labelNotify);
CharSequence text = context.getString(R.string.textNotify);
CharSequence full = context.getString(R.string.fullNotify);
final Notification notification = new Notification(R.drawable.ic_launcher,text,System.currentTimeMillis());
notification.setLatestEventInfo(context,label,full,null);
notification.defaults = Notification.DEFAULT_ALL;
mNotificationManager.notify( 0, notification);
}
}
Taptalked u see .. əəs n pəʞlɐʇdɐʇ
Click to expand...
Click to collapse
I agree, but if he wants to use a dialog, we help him to make one.
The bad thing about the dialog is that it will interrupt whatever the user is doing. This could be very annoying. And who wants to use an app which has annoying popups?
zalez said:
Are you asking how I call the dialog? If so, a simple intent from a broadcast receiver.
Code:
Intent i = new Intent(context, SilentDialog.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
Click to expand...
Click to collapse
When I use this code activity don't shows when I am out of application. For example Handcent SMS when SMS comes to user shows up a great dialog over all windows. My aim is the same thing
DoR2 said:
When I use this code activity don't shows when I am out of application. For example Handcent SMS when SMS comes to user shows up a great dialog over all windows. My aim is the same thing
Click to expand...
Click to collapse
Start an Activity. Set a transparent layout. Show a dialog. That will result in what you want.
nikwen said:
Start an Activity. Set a transparent layout. Show a dialog. That will result in what you want.
Click to expand...
Click to collapse
I have used this code
Code:
Intent i = new Intent(context, SilentDialog.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
and made transparent layout with dialog, but my dialog appears only in my app
DoR2 said:
I have used this code
Code:
Intent i = new Intent(context, SilentDialog.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
and made transparent layout with dialog, but my dialog appears only in my app
Click to expand...
Click to collapse
Could you please post your code?
nikwen said:
Could you please post your code?
Click to expand...
Click to collapse
How I call activity
Code:
if(answer.contains("BEEP")){
Intent intent=new Intent();
intent.setAction("Navi_Beep");
sendBroadcast(intent);
r.play();
Intent i = new Intent(context, NBeep.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
NBeep.java
Code:
public class NBeep extends Activity {
[user=439709]@override[/user]
public void onCreate(Bundle savedInstanceState) {
Log.d("NaviBeep","Here");
//super.onCreate(savedInstanceState);
super.onCreate(savedInstanceState);
AlertDialog alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setTitle("Title");
alertDialog.setMessage("Message");
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent=new Intent();
intent.setAction("Navi_BeepOff");
sendBroadcast(intent);
finish();
}
});
// Set the Icon for the Dialog
alertDialog.show();
}
}
DoR2 said:
How I call activity
Code:
if(answer.contains("BEEP")){
Intent intent=new Intent();
intent.setAction("Navi_Beep");
sendBroadcast(intent);
r.play();
Intent i = new Intent(context, NBeep.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
NBeep.java
Code:
public class NBeep extends Activity {
[user=439709]@override[/user]
public void onCreate(Bundle savedInstanceState) {
Log.d("NaviBeep","Here");
//super.onCreate(savedInstanceState);
super.onCreate(savedInstanceState);
AlertDialog alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setTitle("Title");
alertDialog.setMessage("Message");
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent=new Intent();
intent.setAction("Navi_BeepOff");
sendBroadcast(intent);
finish();
}
});
// Set the Icon for the Dialog
alertDialog.show();
}
}
Click to expand...
Click to collapse
Ah. You need to call setContentView. Create a transparent View and pass it as a parameter.
nikwen said:
Ah. You need to call setContentView. Create a transparent View and pass it as a parameter.
Click to expand...
Click to collapse
Doesn't help:
Code:
public class NBeep extends Activity {
[user=439709]@override[/user]
public void onCreate(Bundle savedInstanceState) {
Log.d("NaviBeep","Here");
View view=new View(this);
view.setBackgroundColor(Color.TRANSPARENT);
setContentView(view);
super.onCreate(savedInstanceState);
AlertDialog alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setTitle("Title");
alertDialog.setMessage("Message");
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent=new Intent();
intent.setAction("Navi_BeepOff");
sendBroadcast(intent);
finish();
}
});
// Set the Icon for the Dialog
alertDialog.show();
}
}
If you use another layout, is the Activity opened?
Is the "Here" written to the log? Is there any Error message?
And I recommend configuring the AlertDialog within the AlertDialog.Builder: http://www.mkyong.com/android/android-alert-dialog-example/
(However, I guess that it will not solve your problem.)
nikwen said:
If you use another layout, is the Activity opened?
Is the "Here" written to the log? Is there any Error message?
And I recommend configuring the AlertDialog within the AlertDialog.Builder: http://www.mkyong.com/android/android-alert-dialog-example/
(However, I guess that it will not solve your problem.)
Click to expand...
Click to collapse
I finally made it!:victory: Here is code:
1) Call dialog:
Code:
NBeep.createDialog(NBeep.DIALOG_ERROR, context);
2) NBeep.java
Code:
public class NBeep extends Activity{
public final static int DIALOG_ERROR = 4;
protected Dialog onCreateDialog(int id) {
Dialog dialog;
switch(id) {
case DIALOG_ERROR:
AlertDialog alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setTitle("Title");
alertDialog.setMessage("Message");
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent=new Intent();
intent.setAction("Navi_BeepOff");
sendBroadcast(intent);
finish();
}
});
alertDialog.setCancelable(false);
dialog = alertDialog;//new AlertDialog.Builder(this).setMessage("ERROR! This is a global dialog\n Brought to you by Sherif").create();
break;
default:
dialog = null;
}
return dialog;
}
[user=439709]@override[/user]
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
showDialog(DIALOG_ERROR);
}
public static void createDialog(int dialog, Context context){
Intent myIntent = new Intent(context, NBeep.class);
myIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(myIntent);
}
}

Categories

Resources