我正在运行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);
然而,这并没有解决我在设备上运行其他应用程序时在后台运行的问题。我使用的设备是华为Honor 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);
}
}
解决我的问题很容易。在您的设置中搜索安全应用程序,找到您的应用程序并将其标记为安全应用程序。它允许您的应用程序在后台运行。否则,华为的任务管理器将继续杀死它。