onTaskRemoved 执行后应用程序崩溃

App crashes after onTaskRemoved executed

我编辑了问题所以它不是重复的 共 this

在 MainActivity 中我正在做一些文件操作。这些操作在单个文件中处理。因此,之后我通过 ForceShut 的意图传递文件。这是因为我想检测用户何时从最近的应用程序中刷出应用程序,也就是说 onTaskRemoved() 被调用,这个文件被删除到其中。现在到目前为止没问题。文件通过意图成功传输,从日志中可以看出调用了 onTaskRemoved()。当我滑动应用程序时,我尝试在 onTaskRemoved() 中删除的文件也被成功删除,并且那里的日志都 运行 正常,直到 "Application Terminated" 显示。但几秒钟后,我收到一个崩溃警报,说应用程序已停止,而应用程序甚至已从最近的应用程序中删除。崩溃虽然连续出现两次,然后没有崩溃出现。可能是什么问题呢 ? :(

我的 MainActivity class 看起来像这样

public MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //several file operations go here <--
    //removed for simplification 
    Intent mIntent = new Intent(this, ForceShut.class);
     mIntent.putExtra("file", file);
    startService(mIntent);
}
}

和 ForceShut class 看起来像这样:

public class ForceShut extends Service {
     File file;

     @Nullable
     @Override
     public IBinder onBind(Intent intent) {
         return null;
     }

     @Override
     public int onStartCommand(Intent intent, int flags, int startId){
         file =(File) intent.getExtras().get("file");
         return START_STICKY;
     }

     @Override
     public void onTaskRemoved(Intent rootIntent){
         if(file.exists())
             file.delete();
     }
}

编辑

因此,正如@CommonsWare 建议我忘记查看 LogCat,而我只查看了 "Run" 选项卡日志。所以我看了看,似乎有一个空指针异常: 原因:java.lang.NullPointerException:尝试在空对象引用 上调用虚拟方法'android.os.Bundle android.content.Intent.getExtras()',所以看起来即使在再次调用 onStartCommand 之后也是如此。为什么刷完app服务还能重启?

编辑 2 正如@Andreas 指出的那样,问题不是重复的。我编辑了问题。但是我自己找到了解决方法。我使用 stopSelf() 关闭了该服务,因为它似乎将应用程序从 Recents 中滑出,并没有摆脱偶尔重新启动的服务。无论如何希望这对任何人都有帮助

Why could the service start over even after app was swiped ?

您已启动 "sticky" 服务。 The system will automatically restart any sticky service until it is explicitly stopped.

 @Override
 public int onStartCommand(Intent intent, int flags, int startId){
     file =(File) intent.getExtras().get("file");
     return START_STICKY;
 }

我没看到你用 stopSelf() 真正停止它的地方。

就您的 NullPointerExceptions 而言,只需在尝试读取对象之前检查对象是否存在。

if (intent != null && intent.hasExtra("file"))
    file =(File) intent.getExtras().get("file");

由于onStartCommand里面的START_STICKY服务重启了。

您需要使用 START_NOT_STICKY 来防止服务重新启动。