报警管理器或服务 我是C++开发人员,开发了我的第一个Android应用程序。我的申请是一种特殊的提醒。我在寻找最好的方法。我尝试过这种方法: 使用服务 使用AlarmManager

报警管理器或服务 我是C++开发人员,开发了我的第一个Android应用程序。我的申请是一种特殊的提醒。我在寻找最好的方法。我尝试过这种方法: 使用服务 使用AlarmManager,android,service,alarmmanager,Android,Service,Alarmmanager,我的问题是,我可以单独使用AlarmManager吗?考虑到我的AlarmManager应该每1秒被触发一次,这是一项耗费CPU时间的任务吗?(似乎每次执行AlarmManager时,都会创建一个新进程(主进程除外),并立即终止该进程) 如果我使用服务,那么我的应用程序应该始终保留在内存中,如果被用户杀死会发生什么 安卓报警(默认安装的应用程序)是如何工作的 如果有任何帮助,我们将不胜感激。请使用一种返回START\u STICKY并使其开始运行的服务。这样,即使系统为了资源而关闭应用程序,您的

我的问题是,我可以单独使用AlarmManager吗?考虑到我的AlarmManager应该每1秒被触发一次,这是一项耗费CPU时间的任务吗?(似乎每次执行AlarmManager时,都会创建一个新进程(主进程除外),并立即终止该进程)

如果我使用服务,那么我的应用程序应该始终保留在内存中,如果被用户杀死会发生什么

安卓报警(默认安装的应用程序)是如何工作的


如果有任何帮助,我们将不胜感激。

请使用一种返回START\u STICKY并使其开始运行的服务。这样,即使系统为了资源而关闭应用程序,您的应用程序也会一直运行,一段时间后它会正常启动并再次运行,关于用户杀掉它,这是一些大的应用程序都在抱怨的事情,就像你在第一次安装Whatsapp时看到的那样。下面是一个服务的示例:

 public class Yourservice extends Service{

@Override
public void onCreate() {
    super.onCreate();
    // Oncreat called one time and used for general declarations like registering a broadcast receiver  
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {

    super.onStartCommand(intent, flags, startId);

// here to show that your service is running foreground     
mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    Intent bIntent = new Intent(this, Main.class);       
    PendingIntent pbIntent = PendingIntent.getActivity(this, 0 , bIntent, Intent.FLAG_ACTIVITY_CLEAR_TOP);
    NotificationCompat.Builder bBuilder =
            new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.ic_launcher)
                .setContentTitle("title")
                .setContentText("sub title")
                .setAutoCancel(true)
                .setOngoing(true)
                .setContentIntent(pbIntent);
    barNotif = bBuilder.build();
    this.startForeground(1, barNotif);

// here the body of your service where you can arrange your reminders and send alerts   
    return START_STICKY;
}

@Override
public IBinder onBind(Intent intent) {
    return null;
}

@Override
public void onDestroy() {
    super.onDestroy();
    stopForeground(true);
}
}
这是执行代码的持续服务的最佳配方