我想尝试使用系统服务,例如wakelock,但出于某种原因,当我运行它时,错误说“系统服务在onCreate()之前不可用于活动”我尝试改变一点通过将newWakeLock移动到oncreate()
但仍然不起作用来查看它是否可以修复它,可以解决这个问题吗?
public class MainActivity extends ListActivity {
String[] activities = {"package1", "package2", "package3"};
private PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
//@SuppressWarnings("deprecation")
private PowerManager.WakeLock wakeLock; //= powerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK, "My Tag");
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
wakeLock = powerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK, "My Tag");
wakeLock.acquire();
this.setListAdapter(new ArrayAdapter (this, android.R.layout.simple_expandable_list_item_1, activities));
}
public void onPause(){
wakeLock.release();
}
public void onResume(){ }
public void onDestroy(){ }
/* public void onListItemClick(ListView, View, int, long){ }*/
}
答案 0 :(得分:0)
这一行:
powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
应放在onCreate
方法中。
在此之前,活动尚未生效,无法访问Android服务。