我正在尝试在前景中获取应用程序的名称。我通过运行后台服务来实现这一点,我已经实现了Runnable每秒运行一次这个服务。除了在Jelly Bean之外,这在所有操作系统中都能正常工作。我的服务被杀了。我知道如果一个应用程序消耗更多的RAM,那么它会杀死可用的后台服务来管理所需的空间。例如高分辨率游戏。但我会丢失数据。我实施了Foreground Services。它的工作正常。我的疑问是,这对物质效率或电池消耗有何影响?除了前景之外还有其他方法吗?
这是我前台提供的服务。
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
ReceiverRunning = true;
context = this;
Intent intent1 = new Intent(this, ComponentSelector.class);
PendingIntent pendingIndent = PendingIntent.getActivity(this, 1, intent1, 0);
Notification mNotification = new Notification(R.drawable.ic_launcher, "BackgroundApp", System.currentTimeMillis());
mNotification.setLatestEventInfo(this, "BatteryUSage", "Click to open to app", pendingIndent);
mNotification.flags = mNotification.flags|Notification.FLAG_ONGOING_EVENT;
startForeground(1000, mNotification);
// Start service if not started.
if (!ForegroundApp.isRunning == true) {
context.startService(new Intent(context, Brightness.class));
}
boolean has_tele = getPackageManager().hasSystemFeature(
PackageManager.FEATURE_TELEPHONY);
if (has_tele == true) {
TelephonyManager teleman = (TelephonyManager) getBaseContext()
.getSystemService(Context.TELEPHONY_SERVICE);
if (teleman != null)
deviceId = teleman.getDeviceId();
}
uId = deviceInfo();
try {
NetworkInfo info = (NetworkInfo) ((ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE))
.getActiveNetworkInfo();
if (info != null) {
Log.d("wifiRun", "Network available");
ConnectivityManager conMan = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo.State wifi = null;
if (conMan.getNetworkInfo(1).isAvailable())
wifi = conMan.getNetworkInfo(1).getState();
if (wifi == NetworkInfo.State.CONNECTED
|| wifi == NetworkInfo.State.CONNECTING) {
wifiCheck = true;
context.startService(new Intent(context, WiFi.class));
Log.d("wifiRun","wifiCheck: " +wifiCheck);
} else {
Log.d("wifiRun","wifiCheck: " +wifiCheck);
}
}
} catch (Exception e) {
e.printStackTrace();
}
// Register for Screen On and Screen Off.
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
intentFilter.addAction(Intent.ACTION_SCREEN_ON);
sReceiver = new ServiceDefinition();
registerReceiver(sReceiver, intentFilter);
//return super.onStartCommand(intent, flags, startId);
return START_STICKY;
}
答案 0 :(得分:0)
我想,别无他法。您也可以使您的服务变得粘性(http://developer.android.com/reference/android/app/Service.html#START_STICKY),但在这种情况下,使服务前景更正确。当然,您的服务会耗尽电池电量,因此请尽量不要在服务中使用“重型”操作。
如果您将提供服务的源代码,我们将检查您是否实现了所有最佳服务。