You
You

Reputation: 28

android broadcastreceiver auto start on boot up

My AndroidManifest.xml contains:

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

and

<receiver android:name=".MyBroadcastReceiver" android:enabled="true" android:exported="false">   <intent-filter> <action android:name="android.intent.action.BOOT_COMPLETED" /> </intent-filter> </receiver>

and MyBroadcastReceiver

class MyBroadcastreceiver extends BroadcastReceiver
{
    @Override
    public void onReceive(Context context, Intent intent)
    {
        context.startService(new Intent(context, MainService.class));
        //Toast.makeText(context, "    O    ", Toast.LENGTH_SHORT).show();
        new AlertDialog.Builder(context)
        .setTitle("OK")
        .setMessage("OK")
        .setPositiveButton("ㅇㅇ", null)
        .setCancelable(false)
        .show();
    }
}

BUT,

I can not see the AlertDialog after reboot.

I launched the application many times too...

How can I make broadcastreceiver autostart after boot up?

Upvotes: 0

Views: 1901

Answers (2)

Hojjat Imani
Hojjat Imani

Reputation: 329

The problem is you are trying to show an AlertDialog from a BroadcastReceiver, which isn't allowed. You can't show an AlertDialog from a BroadcastReceiver. Only activities can display dialogs.

You should do something else, have the BroadcastReceiver start on boot as you do and start an activity to show the dialog.

Add the following Activity to your application

public class AlertActivity extends Activity{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        new AlertDialog.Builder(this)
            .setTitle("OK")
            .setMessage("OK")
            .setPositiveButton("ㅇㅇ", null)
            .setCancelable(false)
            .show();
    }
}

Also don't forget to add the new activity to your manifest.

Then you just need to start the activity in your receiver

@Override
public void onReceive(Context context, Intent intent)
{
    context.startService(new Intent(context, MainService.class));
    context.startActivity(new Intent(context, AlertActivity.class));
}

If this answer was helpful, please click the checkmark under the like button to indicate so.

Upvotes: 1

nkit
nkit

Reputation: 156

Broadcast receiver cannot show dialog. Start an activity instead.

Upvotes: 0

Related Questions