I wanna create android app which after 30 second will display to me AlertDialog
I did it but i wanna make AlertDialog will display any where in android for example in home of android.
like this http://www.papktop.com/wp-content/uploads/2012/01/Popup-Notifier-1.jpg
it is my code (main Activity )
public class MainActivity extends ActionBarActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//EventBus.getDefault().register(this);
mTextField = (TextView) findViewById(R.id.mTextField);
}
public void show(View view) {
final AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
alertDialog.setMessage("Nek Test");
// alertDialog.setIcon(getResources().getDrawable(R.mipmap.notification_image));
alertDialog.setTitle("Reminder");
alertDialog.setPositiveButton("Got it", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
new CountDownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) {
mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
}
public void onFinish() {
mTextField.setText("done!");
alertDialog.show();
}
}.start();
}
}
For show a dialog outside the app, for example over the Home you need to put this permission in the manifest:
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
Create a service like this:
public class AlertService extends Service {
private static Context context;
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
context = this;
final AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
alertDialog.setMessage("Nek Test");
alertDialog.setTitle("Reminder");
/**ADD THIS FOR DISPLAY THE ALERT ANYWHERE*/
alertDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
alertDialog.setPositiveButton("Got it", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
new CountDownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
alertDialog.show();
}
}.start();
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
}//End class
And finally start the service from activity:
startService(new Intent(this, AlertService.class));
and add this line into the "application" tag in the manifest:
<service android:name=".AlertService" />
There are many ways to do this :
1- Implement a service that will start in the main activity and in the service execute a timer, and whenever the timer finishes it will call a broadcast receiver and this receiver will trigger the showing of the alert dialogue.
2- You could use otto : http://square.github.io/otto/
In otto you have to register every activity to otto and unregister onDestroy off course. The timer has to be in an asynctask and on the post execute you post a certain result. Then you subscribe the onAsyncTaskResult in each activity and trigger the alert dialogue there.
3- You also use otto but this time do not subscrib to onAsyncTaskResult and instead of posting in the onPostExecute send a broadcast. Have a broadcast listener ready and on receive show the alert dialogue
This code works best for me without any errors
public class AlertService extends Service {
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
final AlertDialog alertDialog = new AlertDialog.Builder(AlertService.this).create();
alertDialog.setMessage("Nek Test");
alertDialog.setTitle("Reminder");
alertDialog.setButton("Got it", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
/**ADD THIS FOR DISPLAY THE ALERT ANYWHERE*/
alertDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
alertDialog.show();
return flags;
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
Related
I am creating an application which run a service where a function is called repeatedly in 5 seconds. I am able to start the service by clicking a button but cant stop when another button is clicked!
My code is:
public class LocationService extends Service implements LocationListener {
public static final String MyPREFERENCES = "MyPrefs" ;
public static final String TAG = "MyServiceTag";
Timer t;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
}
#Override
public void onDestroy(){
super.onDestroy();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
t = new Timer();
t.scheduleAtFixedRate(
new TimerTask()
{
public void run()
{
startJob();
}
},
0, // run first occurrence immediatetly
5000); // run every 60 seconds
return START_STICKY;
}
#Override
public boolean stopService(Intent name) {
// TODO Auto-generated method stub
t.cancel();
t.cancel();
return super.stopService(name);
}
Starting and stopping is done in another activity.
public void popupstart() {
android.app.AlertDialog.Builder alertDialog = new android.app.AlertDialog.Builder(this);
alertDialog.setTitle("Enable Location Sharing");
alertDialog.setMessage("Enable location sharing will broadcast your location to clients applications. This is a battery draining process and kindly turn off " +
"location sharing after use");
alertDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString("shareLocation", "yes");
editor.commit();
liveStatus = "1";
mFab = (FloatingActionButton)findViewById(R.id.fab);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
mFab.setImageDrawable(ContextCompat.getDrawable(gnavigationActivity.this, R.drawable.locationon));
}
else{
mFab.setImageDrawable(getResources().getDrawable(R.drawable.locationon));
}
if(!isMyServiceRunning(LocationService.class)) {
Toast.makeText(gnavigationActivity.this, "Location Sharing started", Toast.LENGTH_LONG).show();
processStartService(LocationService.TAG);
}
else{
Toast.makeText(gnavigationActivity.this, "Location Sharing already started", Toast.LENGTH_LONG).show();
}
}
});
alertDialog.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.show();
}
public void popupstop() {
android.app.AlertDialog.Builder alertDialog = new android.app.AlertDialog.Builder(this);
alertDialog.setTitle("Stop Location Sharing");
alertDialog.setMessage("You are about to stop location sharing which now will not broadcast location to client users. Are you sure?");
alertDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
processStopService(LocationService.TAG);
Toast.makeText(gnavigationActivity.this, "Location Sharing Stoped", Toast.LENGTH_LONG).show();
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString("shareLocation", "no");
editor.commit();
liveStatus = "0";
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
mFab.setImageDrawable(ContextCompat.getDrawable(gnavigationActivity.this, R.drawable.locationoff));
}
else{
mFab.setImageDrawable(getResources().getDrawable(R.drawable.locationoff));
}
}
});
alertDialog.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.show();
}
private void processStartService(final String tag) {
Intent intent = new Intent(getApplicationContext(), LocationService.class);
intent.addCategory(tag);
startService(intent);
}
private void processStopService(final String tag) {
Intent intent = new Intent(getApplicationContext(), LocationService.class);
intent.addCategory(tag);
stopService(intent);
}
on calling stopService(intent);
the override method onDestroy will start
try to do this
#Override
public void onDestroy(){
super.onDestroy();
t.cancel();
t.cancel();
}
I am trying to open a AlertDialog. When this AlertDialog is opened, the threads need to wait for user input in order to continue its program. I read that I need to lock the object thats need to wait and notified. When I run this code on my phone. The alertdialog won't show, and it looks like the app is looping, because after a few seconds I get a message that the app isn't responding. Below you will find the code I wrote.. By the way. I am a virgin to android programming. So please be gentle :P
public class EditTagActivity extends Activity{
AlertDialog alertDialog;
Runnable h = new Runnable()
{
# Override
public void run()
{
alertDialog.show();
synchronized(g)
{
try
{
Log.d("Threads", "g.wait()");
g.wait();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
};
Runnable g = new Runnable()
{
#Override
public void run()
{
Log.d("Threads", "createAlertDialog()");
createAlertDialog();
runOnUiThread(h);
}
};
public AlertDialog alert;
Runnable test = new dialogManager();
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_tag);
Log.d("Threads", "setup()");
setup();
}
void setup()
{
Log.d("Threads", "g.run()");
g.run();
}
void createAlertDialog()
{
Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Alert");
alert.setMessage("Flaq");
alert.setPositiveButton("OK", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
synchronized(g)
{
Log.d("Threads", "g.notifyAll");
g.notifyAll();
}
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
synchronized(g)
{
Log.d("Threads", "g.notifyAll");
g.notifyAll();
}
}
});
alertDialog = alert.create();
}
}
Instead of Java's Thread and Runnable approach, you should use Android's AsyncTask, It helps you resolve this more simply by overriding the onPreExecute and onPostExecute methods to handle things just before and after running the code in background.
This post has a good example for using the AsyncTask class.
I want to handle unhandled exception in my app without any third-party libraries.
So i write a code.
Activity :
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Thread.setDefaultUncaughtExceptionHandler(new ReportHelper(this));
throw new NullPointerException();
}
My crash handler :
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.MessageQueue;
import android.widget.Toast;
/**
* Created by S-Shustikov on 08.06.14.
*/
public class ReportHelper implements Thread.UncaughtExceptionHandler {
private final AlertDialog dialog;
private Context context;
public ReportHelper(Context context) {
this.context = context;
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage("Application was stopped...")
.setPositiveButton("Report to developer about this problem.", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
})
.setNegativeButton("Exit", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Not worked!
dialog.dismiss();
System.exit(0);
android.os.Process.killProcess(android.os.Process.myPid());
}
});
dialog = builder.create();
}
#Override
public void uncaughtException(Thread thread, Throwable ex) {
showToastInThread("OOPS!");
}
public void showToastInThread(final String str){
new Thread() {
#Override
public void run() {
Looper.prepare();
Toast.makeText(context, "OOPS! Application crashed", Toast.LENGTH_SHORT).show();
if(!dialog.isShowing())
dialog.show();
Looper.loop();
}
}.start();
}
}
When i start app as you see i throwed NullPointerException. Toast in my handling logic was showed, and dialog was showed too. BUT! Dialog clicks was not handling correct. I mean logic in onClick method was not worked. What the problem and how i can fix that?
In my case, I moved AlertDialog.Builder in thread run function like this:
public void showToastInThread(final String str){
new Thread() {
#Override
public void run() {
Looper.prepare();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage("Application was stopped...")
.setPositiveButton("Report to developer about this problem.", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
})
.setNegativeButton("Exit", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Not worked!
dialog.dismiss();
System.exit(0);
android.os.Process.killProcess(android.os.Process.myPid());
}
});
dialog = builder.create();
Toast.makeText(context, "OOPS! Application crashed", Toast.LENGTH_SHORT).show();
if(!dialog.isShowing())
dialog.show();
Looper.loop();
}
}.start();
}
and all thing work perfectly.
Hope this help you.
According this post, the state of the application is unknown, when setDefaultUncaughtExceptionHandler is called. This means that your onClick listeners may not be active anymore.
Why not use this method:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
setContentView(R.layout.main);
Thread.setDefaultUncaughtExceptionHandler(new ReportHelper(this));
throw new NullPointerException();
} catch (NullPointerException e) {
new ReportHelper(this);
}
}
and remove ReportHelper implementing the Thread.UncaughtExceptionHandler interface.
Your method of not explicitly catching exceptions can be seen as an anti-pattern.
Since an exception occurs on the UI-Thread: the state of this thread is probably unexpected
So try simply this in your click handler :
.setNegativeButton("Exit", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
android.os.Process.killProcess(android.os.Process.myPid());
}
});
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Can’t create handler inside thread that has not called Looper.prepare()
I want to call the alertdialogbox in the thread as follows
public class connect implements Runnable
{
public void run() //run method
{
AlertDialog.Builder alert = new AlertDialog.Builder(cordovaExample.activity);
alert.setTitle("Confirm");
alert.setMessage("Are you sure?");
alert.setPositiveButton("YES", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Do nothing but close the dialog
dialog.dismiss();
}
});
alert.setNegativeButton("NO", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Do nothing
dialog.dismiss();
}
});
AlertDialog s = alert.create();
alert.show();
}
}
I am calling this thread from the following activity
public class cordovaExample extends DroidGap
{
Context mcontext;
public static cordovaExample activity;
private static MediaPlayer music=null;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
activity=this;
super.init();
new Thread(new connect(this)).start();
}
}
but its giving error
Can't create handler inside thread that has not called Looper.prepare()
Any help will be appreciated
Write this line in App UI thread
alert.show();
Something like this
MainActivity.this.runOnUiThread(new Runnable() {
public void run() {
alert.show();
}
});
you cant do changes in ui while thread is running.If u want to do so,Use Handler or runOnUiThead or best option is to use AsyncTask.
I am trying to stop a media player and get out of my activity class whenever the stop option of the process dialog is pressed,but by using the below code i am able to getting out of my activity class but unable to stop the media player sound ,and it is running continuously till the thread stop..
Please help me on this matter
Thanx in advance..
public class Test_Service extends Activity {
private MediaPlayer mp;
private Thread welcomeThread;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mp = MediaPlayer.create(Test_Service.this,R.raw.alarm1);
welcomeThread=new Thread() {
int wait = 0;
#Override
public void run() {
try {
super.run();
while (wait <30000) {
mp.start();
sleep(3000);
wait +=3000;
}
} catch (Exception e) {
System.out.println("EXc=" + e);
} finally {
}
}
};
new AlertDialog.Builder(Test_Service.this)
.setTitle("Alarm is running")
.setPositiveButton("Stop",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
mp.stop();
welcomeThread.stop();
Test_Service.this.finish();
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
mp.stop();
Test_Service.this.finish();
}
})
.create().show();
welcomeThread.start();
}
}
First of all, you should use a Handler with it's postDelayed() method to delay the start.
Furthermore you can set the following OnDismissListener on your AlertDialog and stop the player there to avoid code repetition.
dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
mp.release();
handler.removeCallbacks(startingRunnable);
finish();
}
});
MediaPlayer.release() will stop your MediaPlayer and release it. If you want to reuse this MediaPlayer you will have to create a new one after calling release().