Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to launch activity on BroadcastReceiver when boot complete on Android

I use below code to let my app can be auto-launch after boot complete 10 seconds:

public class BootActivity extends BroadcastReceiver {
    static final String ACTION = "android.intent.action.BOOT_COMPLETED";   

    public void onReceive(Context context, Intent intent) {   
        if(intent.getAction().equals(ACTION)) {
            context.startService(new Intent(context,    
                    BootActivity.class));
            try {
                Thread.sleep(10000);
                Intent newAct = new Intent();
                newAct.setClass(BootActivity.this, NewActivity.class);
                startActivity( newAct );
            }
            catch(Exception e) {
                e.printStackTrace();
            }
        }   
    }   
}  

But the setClass and startActivity cannot use here.
How can I modify to set it to launch activity?

like image 564
brian Avatar asked Jul 09 '13 07:07

brian


People also ask

How pass data from BroadcastReceiver to activity in android?

Intent intent = getIntent(); String message = intent. getStringExtra("message"); And then you will use message as you need. If you simply want the ReceiveText activity to show the message as a dialog, declare <activity android:theme="@android:style/Theme.

What is the limit of BroadcastReceiver in android?

As a general rule, broadcast receivers are allowed to run for up to 10 seconds before they system will consider them non-responsive and ANR the app.

What is the use of BroadcastReceiver in android?

Android BroadcastReceiver is a dormant component of android that listens to system-wide broadcast events or intents. When any of these events occur it brings the application into action by either creating a status bar notification or performing a task.


1 Answers

May this help you...

Create class called AutoStart.class

public class AutoStart extends BroadcastReceiver{

    @Override
    public void onReceive(Context context, Intent intent) {
        // TODO Auto-generated method stub
         if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)){
                Intent i = new Intent(context, SochActivity.class);
                i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(i);
            }
    }

Manifest file:

under manifest tag:

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

Under application tag:

        <receiver
            android:name=".AutoStart"
            android:enabled="true"
            android:exported="true" >
            <intent-filter android:priority="500" >
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
        </receiver>
like image 59
Bhavin Nattar Avatar answered Sep 20 '22 18:09

Bhavin Nattar