这是我非常简单的代码:服务开始每5秒+ AlarmManager全自动停止并恢复
应用:
public class MainActivity extends Activity {
/** Called when the activity is first created. */
public Intent myIntent;
public Button OnButton;
public Button OffButton;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
myIntent = new Intent(this, TimerService.class);
OnButton = (Button) findViewById(R.id.onbutton);
OffButton = (Button) findViewById(R.id.offbutton);
OnButton.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
startService(myIntent);
}
});
OffButton.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
stopService(myIntent);
}
});
}
}
服务:
public class TimerService extends Service
{
public AlarmManager Alarmmgr;
public PendingIntent myPendingIntent;
@Override
public void onCreate()
{
Alarmmgr = (AlarmManager) getSystemService(ALARM_SERVICE);
}
public void SimpleMethod()
{
//Here I will do something
}
@Override
public int onStartCommand(Intent intent, int flags, int startId)
{
SimpleMethod();
myPendingIntent = PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
Alarmmgr.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()+5000, myPendingIntent);
return Service.START_NOT_STICKY;
}
@Override
public IBinder onBind(Intent intent)
{
return null;
}
@Override
public void onDestroy()
{
Alarmmgr.cancel(myPendingIntent);
}
}
的问题是,当我开始我的服务,并关闭它的工作30-50分钟的屏幕。在那段时间之后,它停下来10-50分钟,然后再次恢复......我想连续不间断地运行它。我在代码中必须更改什么?我尝试了一个计时器,但是当我关闭屏幕时它不起作用; /。
尝试使你的服务[前景](http://developer.android.com/reference/android/app/Service.html) – yorkw