这是 onStartCommand()
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// Notification creation code
telMgr = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
telMgr.listen(new PSL(), PhoneStateListener.LISTEN_CALL_STATE);
return super.onStartCommand(intent, flags, startId);
}
和 PhoneStateListener 类(在服务类下)
public class PSL extends PhoneStateListener {
public void onCallStateChanged(int state, String incomingNum) {
switch(state) {
case TelephonyManager.CALL_STATE_IDLE:
case TelephonyManager.CALL_STATE_OFFHOOK:
//Work1
break;
case TelephonyManager.CALL_STATE_RINGING:
//Work2
break;
}
}
}
它们都在同一个 .java 文件中
我在一个服务类上有这些代码。
当我从主 Activity 调用 startService()
时,它运行良好。
但是当我的应用程序被任务管理器、Killer 或由于设备内存不足而自动终止时,服务会重新启动但无法正常工作。
当我转到设置 - 应用程序 - 运行时,它显示进程 1 和服务 1,在被杀死之前/之后。但是在被杀死之后,内存共享变为 1/10。我已经尝试过 startForeground() 不要因为我的通知而轻易被杀死 - 它没有用。 (不显示任何通知)
并且还尝试返回 onStartCommand()
:START_STICKY
、START_REDELIVER_INTENT
- 显示相同的结果是否有任何方法可以完全重启或使其不被杀死?
最佳答案
花了几个小时后我发现,对于 Android 2.0 或更高版本,您可以使用 startForeground() 方法在前台启动您的服务。 Documentation provided by Android
启动的服务可以使用 startForeground(int, Notification) API 将服务置于前台状态,系统认为这是用户主动意识到的事情,因此不会在内存不足时被杀死. (在当前前台应用程序的极端内存压力下,服务在理论上仍然有可能被终止,但实际上这不应该是一个问题。) 前台服务被操作系统杀死的机会非常少。但它工作正常。
public class ServicePhoneState extends Service {
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Intent notificationIntent = new Intent(this, MainActivity.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
Notification notification = new NotificationCompat.Builder(this)
.setContentTitle("Music Player")
.setTicker("Google Music Player")
.setContentText("My Music")
.setSmallIcon(R.drawable.ic_bg_icon)
.setPriority(Notification.PRIORITY_MAX)
.setContentIntent(pendingIntent)
.setOngoing(false)
.build();
startForeground(10, notification);
return START_NOT_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
stopForeground(true);
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
关于android (Service & PhoneStateListener) - 当应用程序被任务管理器、 killer 或内存不足杀死时,服务确实重启但不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9787211/