BroadcastReceiver开机启动Service,并在service中启动Notification
1.AndroidMainfest.xml 配置:接收开机广播
<receiver android:name="BootBroadcastReceiver"> <intent-filter> <action android:name="android.intent.action.BOOT_COMPLETED"></action> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </receiver>
?2.BootBroadcastReceiver
public class BootBroadcastReceiver extends BroadcastReceiver{@Override public void onReceive(Context context, Intent intent) { Log.e("TAG", "开机自动服务自动启动....."); //后边的XXX.class就是要启动的服务 Intent serviceIntent = new Intent(context, MyGpsService.class); context.startService(serviceIntent); } }
?3.?MyGpsService
protected void showNotification() { CharSequence from = "IM"; CharSequence message = "IM start up"; Intent intent = new Intent();ComponentName componentName = new ComponentName("com.lixueli", "com.lixueli.Test");intent.setComponent(componentName);intent.setAction("android.intent.action.MAIN");intent.addCategory("android.intent.category.LAUNCHER");intent.addFlags(Notification.FLAG_ONGOING_EVENT); // The PendingIntent to launch our activity if the user selects this notification PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intent, 0); // construct the Notification object. Notification notif = new Notification(R.drawable.ic_launcher, "IMM Still run background!", System.currentTimeMillis()); notif.flags = Notification.FLAG_ONGOING_EVENT ; notif.setLatestEventInfo(this, from, message, contentIntent); // look up the notification manager service NotificationManager nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE); nm.notify(R.string.app_name, notif); }?