BroadcastReceiver开机启动Service,并在service中启动Notification,不能正确运行
public class UpdateService extends IntentService {
public UpdateService() {
super("UpdateService");
System.out.println( "开机自动服务自动启动.....");
}
@Override
protected void onHandleIntent(Intent intent) {
getNotification();
}
@Override
public void onDestroy(){
super.onDestroy();
Log.d("Demo","onDestroy 已执行");
}
public void getNotification() {
NotificationManager manager = (NotificationManager) getSystemService(Service.NOTIFICATION_SERVICE);
Notification notification = new Notification();
notification.tickerText = "来消息了";
notification.icon = R.mipmap.image2;
notification.flags = Notification.FLAG_AUTO_CANCEL;
notification.defaults =Notification.DEFAULT_VIBRATE;
long when = System.currentTimeMillis();
notification.when = when;
Intent intent = new Intent(getApplication(), FoodDetailed.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, Intent.FILL_IN_ACTION);
Notification.Builder builder = new Notification.Builder(this);
builder.setContentTitle("Bmob Test");
builder.setContentText("IM start up");
builder.setSmallIcon(R.drawable.img1);
//Notification builder = new Notification.Builder(this).setTicker("显示于屏幕顶端状态栏的文本").setSmallIcon(R.mipmap .image2).build();
manager.notify(0, notification);
}
}
public class DeviceStartedListener extends BroadcastReceiver {
public DeviceStartedListener() {
}
@Override
public void onReceive(Context context, Intent intent) {
Log.e("TAG", "开机自动服务自动启动.....");
//后边的XXX.class就是要启动的服务
Intent serviceIntent = new Intent(context, UpdateService.class);
context.startService(serviceIntent);
System.out.println( "开机自动服务自动启动.....");
}
}
相关推荐
【Android】开机自启动Service
以上就是关于Android开机自启动Service的实现细节,理解并掌握这些知识点对于开发者来说至关重要,特别是在设计需要在后台持续运行的应用时。
实现Android开机自启动Service的全攻略
Service是Android中用于执行长时间运行操作而不提供用户界面的组件。它可以在后台处理网络访问、播放音乐、执行文件I/O操作等。Service运行在主进程的主线程中,因此它并不适合执行计算密集型任务,这可能会导致应用界面卡顿。BroadcastReceiver的实现类需要继承自并重写onReceive方法,此方法的参数为Context和Intent。Context是广播接收的上下文环境,Intent则是包含广播信息的对象。
实现Android开机自启动Service的完整指南
本文还有配套的精品资源,点击获取 简介:Android中的Service组件用于执行后台任务,而实现开机自启动Service需要监听系统的 ACTION_BOOT_COMPLETED 广播。本文将探讨如何通过注册BroadcastReceiver、创建BootReceiver类、定义AutoRunService服务类、管理Service生命周期、使用Alarm...
Android实现开机自动启动Service或app的方法
为了测试开机启动功能,需要真机设备或者模拟器,并且需要手动重启设备来观察效果,因为模拟器的重启速度很快,可能会导致广播接收器无法正确触发。4.
Android中实现开机自动启动服务(service)实例
在Android开发中,有时我们需要创建一个服务(service),使其在设备开机时自动启动,以便执行一些后台任务或持续运行的功能。


