그러냐

안드로이드 service에서 alert dialog 띄우기 본문

android

안드로이드 service에서 alert dialog 띄우기

관절분리 2016. 1. 28. 10:58
반응형

출처 : http://stackoverflow.com/questions/21283588/pop-up-alert-dialog-box-from-service-in-android

I'm trying to build activity aware app. I used the activity recognition example from android developers as starting point. In this example the moment the user starts moving notification appears with request to turn on the GPS. I'm trying to replace this notification with an alarm dialog box and some sound. the simple and most common alert box that I found is not working for me since it is imposible to create an allert from service. Thanks to Harsh for giving me an idea of activity. I will post the code the moment it will work. Thank you in advance as promised the working code of an alert box invoked from service : 1) the code in the service file:

    Intent intent;
    intent = new Intent(this, MyAlert.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity(intent);

2) the code in the alert activity .java file :

    public class MyAlert extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_my_alert);

    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);

    // set title
    alertDialogBuilder.setTitle("Your Title");

    // set dialog message
    alertDialogBuilder
            .setMessage("Your Message")
            .setCancelable(false)
            .setNeutralButton("OK", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    // if this button is clicked, just close
                    // the dialog box and do nothing
                    stopService(getIntent());
                    dialog.cancel();
                    finish();
                }
            });

    // create alert dialog
    AlertDialog alertDialog = alertDialogBuilder.create();

    // show it
    alertDialog.show();
}

3)alert activity manifest was left empty of code, just a layout 4)the manifest.xml:

    <activity
        android:name="com.igor.map.MyAlert"
        android:theme="@android:style/Theme.Dialog">
    </activity>

All works, one thing still has a problem, when i press the Ok button the allert closes but the label of the app stays until I click on screen.

 

 

 

 

 

 

 

 

 

 

Start an Activity from service, and declare activity as dialog in your manifest. Like this

<activity
        android:name="com.example.DialogActivity"
        android:label="@string/app_name" 
        android:theme="@android:style/Theme.Dialog
반응형