*近要做个大屏的开发板程序,需要长期稳定运行,并开机自启运行此软件。

废话不多说,上代码

开机自启需要广播检测,权限 android.permission.RECEIVE_BOOT_COMPLETED

1、AndroidManifest.xml中加入两行代码,红色代码

<?xml version=”1.0″ encoding=”utf-8″?>
<manifest xmlns:android=”http://schemas.android.com/apk/res/android”
xmlns:tools=”http://schemas.android.com/tools”
package=”包名”>

<uses-permission android:name=”android.permission.ACCESS_WIFI_STATE” />
<uses-permission android:name=”android.permission.CHANGE_WIFI_STATE” />
<uses-permission android:name=”android.permission.ACCESS_NETWORK_STATE” />
<uses-permission android:name=”android.permission.CHANGE_NETWORK_STATE” />
<uses-permission android:name=”android.permission.INTERNET” />
<!– 开机自启动–>
<uses-permission android:name=”android.permission.RECEIVE_BOOT_COMPLETED” />

<application
android:allowBackup=”true”
android:icon=”@drawable/timg”
android:label=”@string/app_name”
android:roundIcon=”@drawable/timg”
android:supportsRtl=”true”
android:theme=”@style/AppTheme”>
<activity android:name=”.MainActivity”>
<intent-filter>
<action android:name=”android.intent.action.MAIN” />

<category android:name=”android.intent.category.LAUNCHER” />
</intent-filter>
</activity>
<activity android:name=”.NetWorkActivity”></activity>
<!– 程序自启动广播 –>
<receiver android:name=”com.wisdtour.interact.Broadcast.MyBroadcastReceiver”
>
<intent-filter>
<action android:name=”android.intent.action.BOOT_COMPLETED”/>
<category android:name=”android.intent.category.LAUNCHER” />
<category android:name=”android.intent.category.HOME” />
</intent-filter>
</receiver>
</application>

</manifest>
2,编写广播接收者

import …;

//开机自启动
public class MyBroadcastReceiver extends BroadcastReceiver {
private final String ACTION_BOOT = “android.intent.action.BOOT_COMPLETED”;

@Override
public void onReceive(Context context, Intent intent) {
Log.e(“TAG”, intent.getAction());
Toast.makeText(context, intent.getAction(), Toast.LENGTH_LONG).show();

/**
* 如果 系统 启动的消息,则启动 APP 主页活动
*/

if (ACTION_BOOT.equals(intent.getAction())) {
Intent intentMainActivity = new Intent(context, MainActivity.class);
intentMainActivity.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intentMainActivity);
Log.e(“TAG”, “开机完毕~——启动MainActivity”);
Toast.makeText(context, “开机完毕~”, Toast.LENGTH_LONG).show();
}
}

}
3,在设置中,允许程序自启动(或各种拦截软件中), 否则将被拦截(一般没有重启应该就是被拦截了)

4,重启试试