如何在Android中使用Alarm Manager启动服务?
在我的应用程序中,我尝试使用Alarm Manager启动服务。 当我点击一个button服务应该开始在我给的特定时间。 我的闹钟pipe理器代码如下:
public void onClick(View view) { if(view == m_btnActivate) { Calendar cur_cal = Calendar.getInstance(); cur_cal.setTimeInMillis(System.currentTimeMillis()); cur_cal.add(Calendar.SECOND, 50); Log.d("Testing", "Calender Set time:"+cur_cal.getTime()); Intent intent = new Intent(DashboardScreen.this, ServiceClass.class); Log.d("Testing", "Intent created"); PendingIntent pi = PendingIntent.getService(DashboardScreen.this, 0, intent, 0); AlarmManager alarm_manager = (AlarmManager)getSystemService(Context.ALARM_SERVICE); alarm_manager.set(AlarmManager.RTC, cur_cal.getTimeInMillis(), pi); Log.d("Testing", "alarm manager set"); Toast.makeText(this, "ServiceClass.onCreate()", Toast.LENGTH_LONG).show(); } }
波纹pipe是我的服务级别:
public class ServiceClass extends Service{ @Override public void onCreate() { // TODO Auto-generated method stub super.onCreate(); Log.d("Testing", "Service got created"); Toast.makeText(this, "ServiceClass.onCreate()", Toast.LENGTH_LONG).show(); } @Override public IBinder onBind(Intent arg0) { // TODO Auto-generated method stub return null; } @Override public void onDestroy() { // TODO Auto-generated method stub super.onDestroy(); } @Override public void onStart(Intent intent, int startId) { // TODO Auto-generated method stub super.onStart(intent, startId); Toast.makeText(this, "ServiceClass.onStart()", Toast.LENGTH_LONG).show(); Log.d("Testing", "Service got started"); } }
如果服务将启动它应该打印服务类中的日志消息。 但它没有显示。 任何人都可以帮忙吗?
这是我用过的,从现在开始30秒后开始服务,
Intent intent = new Intent(DashboardScreen.this, ServiceClass.class); PendingIntent pintent = PendingIntent.getService(DashboardScreen.this, 0, intent, 0); AlarmManager alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE); alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 30*1000, pintent);
试试吧,让我知道发生了什么…
编辑:
在你的manifest.xml文件中
<service android:enabled="true" android:name=".ServiceClass" />
我知道这是一个古老的问题,但只是为了帮助谷歌的人,这里是如何保持您的服务活着。
Intent ishintent = new Intent(this, HeartBeat.class); PendingIntent pintent = PendingIntent.getService(this, 0, ishintent, 0); AlarmManager alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE); alarm.cancel(pintent); alarm.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),5000, pintent);
该服务被杀死并每5秒重新启动一次。