2013-10-26 75 views
3

我是C++开发人员,正在开发我的第一个Android应用程序。我的应用程序是一种特殊的提醒。我正在寻找最好的方式来做到这一点。我曾尝试这个办法:AlarmManager或服务

  1. 使用服务
  2. 使用的AlarmManager

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

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

Android如何报警(默认安装的应用程序)的工作原理?

任何帮助,将不胜感激。

回答

6

使用返回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); 
} 
} 

这是一个持续的服务以执行代码的最佳配方。

+0

感谢您的回复,我会研究/检查它。 –