Dialog from GCM not wakingUp the App - android

I get push notifications, using this message create a Dialog to get the availability. Here I get push notification in Dialog form if the app is already open, if the app is not open, push notification comes and Dialog is not coming, How may I get the Dialog even the app is not open. Here is my Code.
private final BroadcastReceiver mHandleMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String newMessage = intent.getExtras().getString(EXTRA_MESSAGE);
String[] msg = newMessage.split(",");
latitude = Double.parseDouble(msg[0]);
longitude = Double.parseDouble(msg[1]);
glat = msg[0];
glon = msg[1];
ambNo = msg[3];
currIncId = msg[4];
// Waking up mobile if it is sleeping
WakeLocker.acquire(getApplicationContext());
if(newMessage!=null)
{
showAlertDialog(context, msg[2]+" AT", getMyLocationAddress(latitude, longitude), false);
return;
}
WakeLocker.release();
}
};
and this is my Dialog Code:
public void showAlertDialog(final Context context, String title, String message,
Boolean status)
{
dist = String.valueOf(distanceFrom(lat, lon, latitude, longitude));
Log.i("DISTANCE TO MES FOM AMB", dist);
final GPSTracker gps = new GPSTracker(context);
final AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
alertDialog.setTitle(title);
alertDialog.setMessage(message);
alertDialog.setCancelable(false);
// Setting Positive "Yes" Button
alertDialog.setPositiveButton("RESPOND", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
mRegisterTask = new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params){
stat = ServerUtilities.updatestatus(context, ambNo, String.valueOf(gps.getLatitude()), String.valueOf(gps.getLongitude()), "1", currIncId);
return null;
}
#Override
protected void onPostExecute(Void result) {
mRegisterTask = null;
}
};
mRegisterTask.execute(null, null, null);
Intent mrAc = new Intent(context,MapRouteActivity.class);
startActivity(mrAc);
}
});
// Setting Negative "NO" Button
alertDialog.setNegativeButton("DECLINE", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
mRegisterTask = new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
ServerUtilities.updatestatus(context, MainActivity.ambNo, MainActivity.glat, MainActivity.glon, "0",MainActivity.currIncId);
return null;
}
#Override
protected void onPostExecute(Void result) {
mRegisterTask = null;
}
};
mRegisterTask.execute(null, null, null);
dialog.cancel();
}
});
final AlertDialog dlg = alertDialog.create();
alertDialog.show();
// Showing Alert Message
//alertDialog.setIcon(R.drawable.counter);
final Timer t = new Timer();
t.schedule(new TimerTask() {
public void run() {
dlg.dismiss(); // when the task active then close the dialog
t.cancel(); // also just top the timer thread, otherwise, you may receive a crash report
}
}, SPLASH_TIME_OUT); // after 2 second (or 2000 miliseconds), the task will be active.
}
hope to get some good idea.

Dialogs need to have an Activity content. Just giving the application content doesn't work. You will need to start an Activity that looks like a dialog. See Android Activity as a dialog

Related

Unable to close AlertDialog after onResume()

I checking when the activity starts up whether Location Services are turned on or not, if not I am opening a dialog that starts the "Enable Location Activity" intent. Once I am returning from it I am checking if the location has really been enabled or not, if so I am dismissing the alert dialog.
In theory this should work, but when my activity resumes and call dialog.dismiss() absolutely nothing happens.
My code is as follows-:
public class LocationUtils {
private static AlertDialog dialog_ = null;
public static void checkAndEnableLocationServices(final Activity context) {
LocationManager lm = (LocationManager) context.getSystemService(context.LOCATION_SERVICE);
boolean gps_enabled = false;
boolean network_enabled = false;
try {
gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch (Exception ex) {
ex.printStackTrace();
}
try {
network_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch (Exception ex) {
ex.printStackTrace();
}
System.out.println("gps_enabled = " + gps_enabled);
System.out.println("network_enabled = " + network_enabled);
if (!gps_enabled && !network_enabled) {
// notify user
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage("Location services are disabled");
builder.setPositiveButton("Enable Location Services", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
// TODO Auto-generated method stub
Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
context.startActivity(myIntent);
//get gps
}
});
builder.setNegativeButton("Exit", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
context.finish();
}
});
//For future reference.
AlertDialog dialog = builder.create();
dialog_ = dialog;
dialog.show();
} else {
if(dialog_!=null) {
dialog_.dismiss();
}
}
}
}
In my main activity I have a onResume callback that does the following-:
#Override
protected void onResume() {
super.onResume();
System.out.println("Activity resume()");
LocationUtils.checkAndEnableLocationServices(this);
}
What am I missing ? Why is this is dialog not closing ? The code is not throwing any errors. This a WTF moment for me.
Your are calling alertDialog.show method for the local alert dialog.
Replace code,
AlertDialog dialog = builder.create();
dialog_ = dialog;
with
dialog_ = builder.create();
dialog_.show
and onResume()
if(dialog_!=null) {
dialog_.dismiss();
}
Yo can dismiss dialog when positive button clicked and show it in OnResume if Location Service not enambled

Set timeout function with AsyncTask [Android]

In my case, I would like to get the button pressed and get process with the timeout. When button clicked then it will verify the accNo with web services, if the verification (ProgressDialog) is over 5 seconds then it will stop and display the alertDialog to notice user "Timeout".
But now I have not idea when I in testing with 1 milliseconds, in logically it will pause in alertDialog until get pressed, but now it will display the dialog in milliseconds then auto dismiss and intent to next activity. Here is my code:
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_information3);
btn_next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (title.getText().toString().equals("INFO")) {
InfoAsyncTask infoAsyncTask = new InfoAsyncTask();
try {
infoAsyncTask.execute().get(1, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (TimeoutException e) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(Information3.this);
alertDialog.setTitle(":: Error ::");
alertDialog.setMessage("Verify Timeout. Please try again.");
alertDialog.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
}
}
});
}
private class InfoAsyncTask extends AsyncTask<Void, Void, String> {
private String results;
private ProgressDialog pDialog;
private Object resultRequestSOAP;
String accNo = et_accNo.getText().toString().trim();
int timeout = 15000;
#Override
protected void onPreExecute() {
pDialog = new ProgressDialog(Information3.this);
pDialog.setMessage("Verifying...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
super.onPreExecute();
}
#Override
protected String doInBackground(Void... params) {
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
request.addProperty("Code", InfoCode);
request.addProperty("AccNo", accNo);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL, timeout);
androidHttpTransport.debug = true;
try {
androidHttpTransport.call(SOAP_ACTION, envelope);
String requestDumpString = androidHttpTransport.requestDump;
Log.d("request Dump: ", requestDumpString);
} catch (Exception e) {
e.printStackTrace();
}
try {
resultRequestSOAP = envelope.getResponse();
results = resultRequestSOAP.toString();
Log.d("Output: ", results);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String result) {
if (resultRequestSOAP == null) {
if (pDialog.isShowing()) {
pDialog.dismiss();
} else {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(Information3.this);
alertDialog.setTitle(":: Error ::");
alertDialog.setMessage("Connection error, please check your internet connection.");
alertDialog.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
pDialog.dismiss();
}
} else {
if (results.equals("false")) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(Information3.this);
alertDialog.setTitle(":: Warning ::");
alertDialog.setMessage("Please fill in correct account number");
alertDialog.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
} else if (et_billNo.getText().toString().trim().isEmpty()) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(Information3.this);
alertDialog.setTitle(":: Warning ::");
alertDialog.setMessage("Please fill in bill number");
alertDialog.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
} else if (et_amountNo.getText().toString().trim().isEmpty() || Integer.parseInt(et_amountNo.getText().toString().trim()) <= 0) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(Information3.this);
alertDialog.setTitle(":: Warning ::");
alertDialog.setMessage("Please fill in amount");
alertDialog.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
} else if (results.equals("true")) {
Title = title.getText().toString();
String value1 = et_accNo.getText().toString().trim();
String value2 = et_billNo.getText().toString().trim();
int value3 = Integer.parseInt(et_amountNo.getText().toString().trim());
addSearchInput(value1);
addSearchInput(value2);
addSearchInput(String.valueOf(value3));
Intent intent = new Intent(Information3.this, confirmation3.class);
intent.putExtra("name", Title);
intent.putExtra("value1", value1);
intent.putExtra("value2", value2);
intent.putExtra("value3", value3);
startActivity(intent);
} else {
super.onPreExecute();
}
pDialog.dismiss();
}
}
}
get() method will block the UI thread and I guess you don't want this.
You should implement cancel mechanics in doInBackground and call AsyncTask.cancel() by timeout [like that](https://developer.android.com/reference/android/os/Handler.html#postDelayed(java.lang.Runnable, long))
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
AsyncTask.cancel();
}
}, 1);
Be aware there are many gotchas with AsyncTask, check my article.

Show AlertDialog in IntentService

How to show AlertDialog in IntentService? Error looks like:
Unable to add window -- token null is not for an application.
So this is problem with context, but I don't know how to fix it. Any solutions?
Below there is my code:
public class GcmMessageHandler extends IntentService {
private GoogleCloudMessaging gcm;
private static AlertDialog alert;
String mes;
private Handler handler;
public GcmMessageHandler() {
super("GcmMessageHandler");
}
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
handler = new Handler();
}
#Override
protected void onHandleIntent(Intent intent) {
Bundle extras = intent.getExtras();
gcm = GoogleCloudMessaging.getInstance(this);
String messageType = gcm.getMessageType(intent);
mes = extras.getString("message");
MApp.wakeupSync();
showToast();
Log.i("GCM", "Received : (" + messageType + ") " + extras.getString("message"));
GcmBroadcastReceiver.completeWakefulIntent(intent);
}
#Override
public void onDestroy() {
try {
gcm.unregister();
} catch (IOException e) {
e.printStackTrace();
}
}
public void showToast(){
handler.post(new Runnable() {
public void run() {
AlertDialog.Builder builder = new AlertDialog.Builder(getApplicationContext());
builder.setMessage("TEST")
.setCancelable(false)
.setNegativeButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
alert = builder.create();
alert.show();
}
});
}
}
You can only show AlertDialog using Activity context.
Here you use getApplicationContext() to create builder, but
neither Application context nor Service context will work.
You have to send broadcast/intent to some Activity and as a response to this message show an AlertDialog inside this Activity using Activity context.
Read this for more details:
https://possiblemobile.com/2013/06/context/
Define a handler in your Activity
/**
* Response handler
*/
private Handler handlerResponse = new Handler() {
#Override
public void handleMessage(Message msg) {
//Show your alert here
}
};
Start service along with Messenger
Intent intent = new Intent(getActivity(), CommunicationService.class);
intent.setAction(Constants.ACTION_ONE);
intent.putExtra(Constants.EXTRA_MESSENGER, new Messenger(handlerResponse));
startService(intent);
In your service return the message after completing the functionality
protected void onHandleIntent(Intent intent) {
if (intent != null) {
sendResult(intent, result);
}
}
private void sendResult(Intent intent, String result) {
Bundle extras = intent.getExtras();
if (extras != null) {
Messenger messenger = (Messenger) extras.get(Constants.EXTRA_MESSENGER);
Message msg = Message.obtain();
msg.obj = result;
try {
messenger.send(msg);
} catch (Exception e1) {
Log.e(getClass().getName(), "Exception sending message", e1);
}
}
}
Constants
public static final String EXTRA_MESSENGER = "EXTRA_MESSENGER";
public static final String ACTION_ONE = "INIT_SOCKET";

Android App crash with dialog

I`m getting the GPS coordination of the device inside an AsyncTask class (by getLocation method) but, If the GPS is disable, I open a dialog that able the user to transfer to the "setting" area and turn the GPS "on" or cancel. The App crash every time the the dialog alert has open before the user even press at one of the buttons. How can I solve it ?
public class StarTask extends AsyncTask<Void,Void,ArrayList<Song>>{
final int k_ThreadSleepTime = 3000;
final int k_MaxThreadTries = 7;
double latitude = 0;
double longitude = 0;
GPSTracker gps;
TestMain client;
#Override
protected void onPreExecute() {
super.onPreExecute();
gps = new GPSTracker(getApplication());
}
#Override
protected ArrayList<Song> doInBackground(Void... params) {
ArrayList<Song> list = new ArrayList();
client = new TestMain();
int tries = 0;
String o;
getLocation();
String url = builtURL();
try {
String jsonPageStr = client.doGetRequest(url);
JSONObject obj = new JSONObject(jsonPageStr);
userId = obj.getJSONObject("info").getInt("user_id");
isWait = (wait.equals("true"));
while (isWait && tries < k_MaxThreadTries) {
url = builtURL();
jsonPageStr = client.doGetRequest(url);
obj = new JSONObject(jsonPageStr);
if (!(obj.equals("") || obj.equals(null))) {
isWait = (wait.equals("true"));
}
tries++;
try {
Thread.sleep(k_ThreadSleepTime);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if(tries == k_MaxThreadTries) {
//exit the App
onMyDestroy();
}
}
private String builtURL() {}
private void getLocation() {
if (gps.canGetLocation()) {
latitude = gps.getLatitude();
longitude = gps.getLongitude();
} else {
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
//gps.showSettingsAlert();
showSettingsAlert();
}
gps.stopUsingGPS();
}
public void showSettingsAlert(){
runOnUiThread(new Runnable() {
#Override
public void run() {
final AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this);
// Setting Dialog Title
alertDialog.setTitle("GPS is settings");
// Setting Dialog Message
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
// On pressing Settings button
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
MainActivity.this.startActivity(intent);
hasBeenNoGps = true;
}
});
// on pressing cancel button
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
hasBeenNoGps = true;
onMyDestroy();
}
});
// Showing Alert Message
alertDialog.show();
}
});
}
#Override
protected void onPostExecute(ArrayList<Song> aVoid) {
super.onPostExecute(aVoid);
You're doing UI operations on showSettingsAlert() which is called during doInBackground() of your AsyncTask. The allowed approach is to keep all operations involving UI away from doInBackground(). Here you could remove the else condition from getLocation() and rather implement it onPreExecute(). Like this,
public class StarTask extends AsyncTask<Void,Void,ArrayList<Song>>{
final int k_ThreadSleepTime = 3000;
final int k_MaxThreadTries = 7;
double latitude = 0;
double longitude = 0;
GPSTracker gps;
TestMain client;
#Override
protected void onPreExecute() {
super.onPreExecute();
gps = new GPSTracker(getApplication());
if (!gps.canGetLocation()) {
showSettingsAlert();
}
}
#Override
protected ArrayList<Song> doInBackground(Void... params) {
ArrayList<Song> list = new ArrayList();
client = new TestMain();
int tries = 0;
String o;
getLocation();
String url = builtURL();
try {
String jsonPageStr = client.doGetRequest(url);
JSONObject obj = new JSONObject(jsonPageStr);
userId = obj.getJSONObject("info").getInt("user_id");
isWait = (wait.equals("true"));
while (isWait && tries < k_MaxThreadTries) {
url = builtURL();
jsonPageStr = client.doGetRequest(url);
obj = new JSONObject(jsonPageStr);
if (!(obj.equals("") || obj.equals(null))) {
isWait = (wait.equals("true"));
}
tries++;
try {
Thread.sleep(k_ThreadSleepTime);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if(tries == k_MaxThreadTries) {
//exit the App
onMyDestroy();
}
}
private void getLocation() {
if (gps.canGetLocation()) {
latitude = gps.getLatitude();
longitude = gps.getLongitude();
}
gps.stopUsingGPS();
}
You are trying to run a UI thread in a background thread (inside your AsyncTask), what you can do is create a global dialog in your AsyncTask class and show it on doInBackground method and then close it onPostExecute(). You will need a Context for your dialog.

How to show a progress bar in android while waiting to recieve an sms for 5 mintues?

My Question
How to show a progress bar in android while waiting to receive an SMS?
The dialog should fulfill the following conditions
The dialog should be dismissed in maximum for 5 minutes.
The dialog should be dismissed if SMS is received before 5 minutes.
What I tried
public class GetSMS extends Activity {
...
...
private boolean progressDialogFlag;
private ProgressDialog progressDialog;
...
...
new SMSReceiver().execute();
}
public class SMSReceiver extends AsyncTask<Void, Integer, Void> {
protected void onPreExecute() {
// start a progressdialog box
super.onPreExecute();
progressDialogFlag = true;
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setMessage("Waiting to Receive SMS...");
progressDialog.setCancelable(false);
progressDialog.show();
}
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
if (progressDialogFlag == true) {
progressDialog.setProgress(progress[0]);
}
if (progress[0] == 100 || progressDialogFlag == false) {
progressDialog.dismiss();
}
}
protected void onPostExecute(Void result) {
}
#Override
protected Void doInBackground(Void... params) {
int interval = 2;
int totalDuration = 5 * 60 * 1000; // 5 min
int sleepPeriod = (totalDuration / 100) * interval;
for (int i = 2; i <= 100; i += 2) {
publishProgress(i);
try {
Thread.sleep(sleepPeriod);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return null;
}
}
smsReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
progressdialog = false;
}
}
What are my doubts
I think the use of progressDialogFlag to dismiss the progressDialog when an Sms is received before 5 min is causing the problem.
The use of variable progressDialogFlag in UI and worker thread is causing some kind of race condition.
Thanks for help.
can try some thing like below when you start the progressDialog
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
if(null!=progressDialog && progressDialog.isShowing()){
// try{
progressDialog.dismiss();
}
}
}, 5*60*1000);
but need some more checks......
Do like this:
private ProgressDialog p;
private void sendSMS(){
p = new ProgressDialog(Context);
registerReceiver(broadcastReceiver, SMSINTENT);
}
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
p.dismiss();
getActivity().unregisterReceiver(this);
}
};
Don't know if it is the best solution, but it works!

Categories

Resources