4

I'm a C++ developer and developing my first Android application. My application is an special kind of Reminder. I'm looking for the best way to do it. I have tried this approaches:

  1. Use a Service
  2. Use an AlarmManager

My question is that can I use AlarmManager singly? Is it a CPU time consuming task considering that my AlarmManager should be fired every 1 second ? (It seems that every time an AlarmManager is executed a new process except main process is created and immediately is killed).

If I use a service then my application should always stay in memory and also what happens if is killed by user !?

How Android Alarms (default installed application) works?

Any help would be appreciated.

4

1 回答 1

8

使用返回 START_STICKY 的服务并将其设为 startForeground,这样您的应用程序将一直运行,即使系统在一段时间后将其杀死以获取资源,它也会正常启动并再次运行,并且关于用户杀死它,这甚至是大型应用程序抱怨像您在第一次安装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);
}
}

这是执行代码的持续服务的最佳方法。

于 2013-10-29T11:57:56.380 回答