Saturday, October 27, 2012

Show Dialog in Android After Device Boot Is Finished

What to do if you want to show an alert dialog right after the device boot is finished? You receive ACTION_BOOT_COMPLETED but you can't show an alert dialog from the broadcast receiver if you don't have any activities. Thus, what you need is to create one. But if you want your users to see only the dialog, your activity must be completely transparent.

1. Transparent activity style.
First, you need to create a transparent activity. Add this style to styles.xml:

Any activity that has this style as a theme will be transparent.

2. Activity with a simple dialog.
Now lets create an activity that will show a simple dialog:
public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("Message")
               .setTitle("Title")
               .setCancelable(false)
               .setPositiveButton("OK", new DialogInterface.OnClickListener()
               {
                   public void onClick(DialogInterface dialog, int id) 
                   {
                       MainActivity.this.finish();
                   }
               });
  
  
        AlertDialog alert = builder.create();
        alert.show();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
}
3. Broadcast receiver.
Obviously you need a broadcast receiver that handles ACTION_BOOT_COMPLETED broadcast (note that you need a permission to receive the broadcast):
public class OnBootReceiver extends BroadcastReceiver
{
    @Override
    public void onReceive(Context context, Intent intent)
    {  
        Intent startIntent = new Intent(context, MainActivity.class);
        startIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(startIntent);
    }
}
4. Android manifest
In your manifest you must assign the created style for your activity and register the broadcast receiver. It should look something like this (note that you need a permission to receive the broadcast):


    
    

    
        
            
                

                
            
        
        
        
            
                
            
        
    


That's pretty much all you need to show a dialog after the device's boot is complete. Source code can be obtained from Github.

2 comments:

  1. @android:color/transparent
    is giving an error in styles.xml file apart from it tutorial is good

    ReplyDelete
  2. got it working fine thanks for the tutorial..

    ReplyDelete