您的位置:首页 > 移动开发 > Android开发

在android系统启动时获取通知

2014-08-03 15:44 281 查看
android系统在Manifest.permission中有这样一条RECEIVE_BOOT_COMPLETED的定义,当你自己的程序加入这个权限后,就可以在系统启动完毕后收到一条系统的广播,这个广播的标志为ACTION_BOOT_COMPLETED,因此我们只要定义一个BroadcastReceiver用来接收这个广播,然后加入自定义的动作即可。代码如下:

public class LocationLoggerServiceManager extends BroadcastReceiver {
public static final String TAG = "customTag";
@Override
public void onReceive(Context context, Intent intent) {
if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) {
ComponentName comp = new ComponentName(context.getPackageName(), MainActivity.class.getName());

context.startActivity(new Intent().setComponent(comp).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
} else {
Log.e(TAG, "Received unexpected intent " + intent.toString());
}
}
}
在AndroidManifest.xml中加入这个类的定义和权限说明

<receiver
android:name=".LocationLoggerServiceManager"
android:enabled="true"
android:exported="false"
android:label="LocationLoggerServiceManager">
<intent-filter>
<action
android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Android