我正在运行 cwac-locpoll 的演示示例。它旨在每分钟在 LocationLog.txt 文件中记录我的位置。只要应用程序在屏幕上,它就可以正常工作,但是如果我按下主页按钮,它会停止记录,当我返回应用程序时,它会再次重新加载。当我在屏幕上运行时锁定屏幕时发生了同样的事情,但我强迫应用程序休眠:
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
但是,当我在设备上运行其他应用程序时,这并没有解决在后台运行的问题。我使用的设备是华为荣耀7
我的 MainActivity 的整个代码如下:
public class MainActivity extends AppCompatActivity {
private static final int PERIOD= 1000 * 60 * 1; // 1 minute
private PendingIntent pi=null;
private AlarmManager mgr=null;
PowerManager pm;
PowerManager.WakeLock wl;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final TextView test = (TextView) findViewById(R.id.testTV);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
mgr=(AlarmManager)getSystemService(ALARM_SERVICE);
Intent i=new Intent(this, LocationPoller.class);
i.putExtra(LocationPoller.EXTRA_INTENT,
new Intent(this, LocationReceiver.class));
i.putExtra(LocationPoller.EXTRA_PROVIDER,
LocationManager.GPS_PROVIDER);
pi=PendingIntent.getBroadcast(this, 0, i, 0);
mgr.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
SystemClock.elapsedRealtime(),
PERIOD,
pi);
Toast
.makeText(this,
"Location polling every 1 minutes begun",
Toast.LENGTH_LONG)
.show();
}
@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);
}
}