且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在设备启动运行Android应用程序?

更新时间:2023-01-25 22:10:14

如果您在设备上电后,应该是可见的用户界面,使之成为一个主屏幕。

I need to run my application when the device is boot up. I tried the following code. Here my problem is, when i run my application once and i restart my device means it works, if i switch off my device and then switched on means auto run won't works. Why it will happens?

MainActivity.java

public class MainActivity extends Activity {

    ImageView mImageView;
    Button swap_btn;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mImageView = (ImageView) findViewById(R.id.imageView1);
        swap_btn = (Button) findViewById(R.id.button1);
        mImageView.setImageResource(R.drawable.image_01);
        swap_btn.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                // TODO Auto-generated method stub

                mImageView.setImageResource(R.drawable.image_02);

            }
        });
    }

}

OpenOurAppReceiver.java

public class OpenOurAppReceiver extends BroadcastReceiver {


    @Override
    public void onReceive(Context context, Intent intent) {
        Intent i = new Intent(context, MainActivity.class);
        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(i);
    }

}

Manifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.bootup_sample_app"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="15" />

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

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/title_activity_main" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <receiver
            android:name=".OpenOurAppReceiver"
            android:enabled="true"
            android:permission="android.permission.RECEIVE_BOOT_COMPLETED" >
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />

                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </receiver>
    </application>

</manifest>

If you have a user interface that should be visible when the device is powered on, make it be a home screen.