android ICS : service restart hang on intent. getExtras()

标签 android service android-4.0-ice-cream-sandwich restart

我有一个 Activity ,在它的 OnCreate 中:

    serviceIntent = new Intent(this, MyServ.class);
    int templen =  myString.length();
    Log.i("check", "mystring"+templen);     
    serviceIntent.putExtra("myString", myString);       
    startService(serviceIntent);

在服务中,

public int onStartCommand(Intent intent, int flags, int startId) {
    // TODO Auto-generated method stub      
    myString = intent.getExtras().getString("myString");
    return START_STICKY;
}

它工作正常。然后我打开了许多应用程序,让 android 关闭我的应用程序/服务以释放一些内存。如您所料,使用 START_STICKY,服务将尝试重新启动,但未能重新启动。错误日志为:

引起:java.lang.NullPointerException 在 com.example.myapp.myserv.onStartCommand(MyServ.java:77),它指向这一行:

myString = intent.getExtras().getString("myString");

所以我相信当服务重新启动时 myact 没有发送任何 Intent 。我应该如何处理这种情况?谢谢

最佳答案

如果您返回 START_STICKY,文档会说:

if this service's process is killed while it is started (after returning from onStartCommand(Intent, int, int)), then leave it in the started state but don't retain this delivered intent. Later the system will try to re-create the service. Because it is in the started state, it will guarantee to call onStartCommand(Intent, int, int) after creating the new service instance; if there are not any pending start commands to be delivered to the service, it will be called with a null intent object, so you must take care to check for this.

如果您返回的不是 START_STICKY,而是 START_REDELIVER_INTENT,文档中说:

if this service's process is killed while it is started (after returning from onStartCommand(Intent, int, int)), then it will be scheduled for a restart and the last delivered Intent re-delivered to it again via onStartCommand(Intent, int, int). This Intent will remain scheduled for redelivery until the service calls stopSelf(int) with the start ID provided to onStartCommand(Intent, int, int). The service will not receive a onStartCommand(Intent, int, int) call with a null Intent because it will will only be re-started if it is not finished processing all Intents sent to it (and any such pending events will be delivered at the point of restart).

所以,在我看来你要么需要返回 START_STICKY 并了解在重新启动时 onStartCommand() 将被调用并带有 null Intent 对象 您需要返回 START_REDELIVER_INTENT 并了解如果您的服务当前未在被终止时执行 onStartCommand() 方法它根本不会重新启动。

如果您需要保存 myString 的最新值,您可以将其写入共享首选项。

关于android ICS : service restart hang on intent. getExtras(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17430690/

相关文章:

android - 如何为所有 Activity 设置固定方向

android - 不同颜色的布局

android - 如何使用自定义 key 编写 MifareClassic

安卓 : Where to store my Database : Service or Activity?

android - 我如何在 android 中创建一个 Tag 对象?

android - AndroidManifest 中的多个 ComponentDiscoveryService --> 合并冲突

java - 骡子 ESB : Connect to https service

android - 永不过时的服务

Android NDK 使用多核 cpu

android - ADK 1.0 设备无法与 Jelly Bean 一起使用,为什么?