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);
}
本文介绍了如何在Android系统启动时自动启动服务,并通过通知提醒用户。通过配置AndroidManifest.xml中的BootBroadcastReceiver来响应系统开机事件,进而启动指定的服务。同时,通过自定义通知展示服务启动状态。
1094

被折叠的 条评论
为什么被折叠?



