我创建了简单的服务,必须每隔一秒记录一次。我使用了报警管理器(因为从official document说Note: The Alarm Manager is intended for cases where you want to have your application code run at a specific time, even if your application is not currently running.
),但它随机重复。 这里是我的代码报警管理器在服务中重复出现异常
MainActiviry.class
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
if (fab != null) {
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this,LogService.class);
startService(intent);
}
});
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
我通过点击按钮FAB启动服务。
LogService.class
public class LogService extends Service {
private static final String TAG = LogService.class.getSimpleName();
public LogService() {
super();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e(TAG, "onStartCommand: Service calling");
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
super.onDestroy();
}
@Override
public void onCreate() {
Timer(this);
super.onCreate();
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
private void Timer(Context context){
Intent intent = new Intent(context,LogService.class);
PendingIntent pendingIntent = PendingIntent.getService(context,0,intent,0);
AlarmManager alarmManager = (AlarmManager) getApplicationContext().getSystemService(getApplicationContext().ALARM_SERVICE);
alarmManager.setRepeating(alarmManager.RTC_WAKEUP,System.currentTimeMillis(),1*1000,pendingIntent);
}
}
这是我LOG
它重复的每一分钟,但我写的每一秒。我做错了吗?
但[官方文档(http://developer.android.com/reference/android/app/AlarmManager.html)说'的official documentation
简单的解决方案注意:报警管理器适用于您希望在特定时间运行应用程序代码的情况,即使您的应用程序当前未运行。所以我使用它,您是否可以显示一次性精确警报的样本? – Kathi
如果你只是想要一个简单的计时器每秒做一些事情,你也可以使用java Timer类。另一个解决方案是处理程序,取决于你真正想要做什么 – Erich
嗯,谢谢我将使用简单的处理程序,有没有机会用报警管理器来实现这一点? – Kathi