BroadcastReceiver开机启动Service,并在service中启动Notification

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

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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);
    }
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值