Android 为什么我的服务是强制关闭?

Android 为什么我的服务是强制关闭?,android,android-service,Android,Android Service,我在android上编写了一个应用程序和服务。我的应用程序和服务正在相互对话。即使我按下home(主页)按钮或back(返回)按钮并退出我的应用程序,一切都很好,但我的服务仍在运行并完成它的工作。 但问题是: 在我手机附带的屏幕截图中。当我长按home按钮时,有一个关于最近打开的应用程序的布局,如果我按clear all并删除我的应用程序,我的服务将强制关闭, 我的意思是,即使我清除了手机上的所有应用程序,我也希望我的服务仍在运行 这是我的代码: public class myservice

我在android上编写了一个应用程序和服务。我的应用程序和服务正在相互对话。即使我按下home(主页)按钮或back(返回)按钮并退出我的应用程序,一切都很好,但我的服务仍在运行并完成它的工作。 但问题是: 在我手机附带的屏幕截图中。当我长按home按钮时,有一个关于最近打开的应用程序的布局,如果我按clear all并删除我的应用程序,我的服务将强制关闭, 我的意思是,即使我清除了手机上的所有应用程序,我也希望我的服务仍在运行

这是我的代码:

public class myservice  extends Service  { 
    String sourceFileUri;
     
 
    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }
    @Override
    public void onCreate() {
       }
   
    @Override
    public void onStart(Intent intent, int startId) {
        // For time consuming an long tasks you can launch a new thread here..
   
    }
    @Override 
    public int onStartCommand(Intent intent, int flags, int startId) {
         upLoadServerUri= intent.getStringExtra("upLoadServerUri"); 
          try {
         UploaderFoto ups = new UploaderFoto( sourceFileUri  );//this upload image to server
         ups.execute(execute) ;
        } catch (Exception e) {
            // TODO: handle exception
        }
       
        return super.onStartCommand(intent, flags, startId);
    }
    @Override
    public void onDestroy() { 
        //Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
    }
    

     
public class UploaderFoto  extends AsyncTask<String, String, String> {

    HttpURLConnection conn = null;
    DataOutputStream dos = null; 
    String lineEnd = "\r\n";
    String twoHyphens = "--";
    String boundary = "*****";
    int bytesRead, bytesAvailable, bufferSize;
    byte[] buffer;
    int maxBufferSize = 1 * 1024 * 1024; 
    InputStream inputStream = null;
    String result = "";   
     
    String sourceFileUri ; 
    String upLoadServerUri ; 
    String fileName  ; 
     
    public UploaderFoto( String sourceFileUri  ) {  
        this.sourceFileUri=sourceFileUri; 
    }

    @Override
    protected void onPreExecute() { 
        mNotificationHelper.createNotification();   
    }

    @Override
    protected String doInBackground(String... params) {
        File sourceFile = new File(sourceFileUri); 
        
        @SuppressWarnings("unused")
        int serverResponseCode = 0;
        try {
 
            // open a URL connection to the Servlet
            FileInputStream fileInputStream = new FileInputStream(sourceFile);

            // ------------------ CLIENT REQUEST
            URL url = new URL(upLoadServerUri);

            // Open a HTTP connection to the URL
            conn = (HttpURLConnection) url.openConnection();
            conn.setDoInput(true); // Allow Inputs
            conn.setDoOutput(true); // Allow Outputs
            conn.setUseCaches(false); // Don't use a Cached Copy

            // Use a post method.
            //I set here conn parameters

            dos = new DataOutputStream(conn.getOutputStream());

            dos.writeBytes(twoHyphens + boundary + lineEnd);

            dos.writeBytes("Content-Disposition: form-data; name=\"file_name\";filename=\""
                + fileName + "\"" + lineEnd);

            dos.writeBytes(lineEnd);


                // create a buffer of maximum size
            bytesAvailable = fileInputStream.available();

            int streamSize = (int) sourceFile.length();
            bufferSize = xxx;

            buffer = new byte[streamSize];
            int sentBytes=0;
            // read file and write it into form...
            bytesRead = fileInputStream.read(buffer, 0, bufferSize); 
            while (bytesRead > 0) {   
            dos.write(buffer, 0, bufferSize);
            bytesAvailable = fileInputStream.available();
            // bufferSize = Math.min(bytesAvailable, maxBufferSize);
            bytesRead = fileInputStream.read(buffer, 0, bufferSize); 
            }

            // send multipart form data necesssary after file data...
            dos.writeBytes(lineEnd);
            dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
 
            // Responses from the server (code and message)
            serverResponseCode = conn.getResponseCode();  
            fileInputStream.close();  
            dos.flush();
            dos.close();
            
        } catch (MalformedURLException ex) {
            ex.printStackTrace();
             Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
        } catch (Exception e) {
            e.printStackTrace();
        }
       
            
        return result;

    } // protected Void doInBackground(String... params)
   
    @Override
    protected void onPostExecute(String string) {
         
            try {
                stopSelf();
            } catch (Exception e) {
                // TODO: handle exception
            }
                
        
    }  

} 
}
  <service
            android:name="com.xx.yy.myservice" 
            android:enabled="true" 
            android:process =":remote"
             >
   </service>
03-28 07:40:58.937: E/AndroidRuntime(12068): FATAL EXCEPTION: main
03-28 07:40:58.937: E/AndroidRuntime(12068): Process: com.xx.yy:remote, PID: 12068
03-28 07:40:58.937: E/AndroidRuntime(12068): java.lang.RuntimeException: Unable to start service com.xx.yy.myservice@42faa538 with null: java.lang.NullPointerException
03-28 07:40:58.937: E/AndroidRuntime(12068):    at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:2726)
03-28 07:40:58.937: E/AndroidRuntime(12068):    at android.app.ActivityThread.access$2100(ActivityThread.java:139)
03-28 07:40:58.937: E/AndroidRuntime(12068):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1297)
03-28 07:40:58.937: E/AndroidRuntime(12068):    at android.os.Handler.dispatchMessage(Handler.java:102)
03-28 07:40:58.937: E/AndroidRuntime(12068):    at android.os.Looper.loop(Looper.java:136)
03-28 07:40:58.937: E/AndroidRuntime(12068):    at android.app.ActivityThread.main(ActivityThread.java:5105)
03-28 07:40:58.937: E/AndroidRuntime(12068):    at java.lang.reflect.Method.invokeNative(Native Method)
03-28 07:40:58.937: E/AndroidRuntime(12068):    at java.lang.reflect.Method.invoke(Method.java:515)
03-28 07:40:58.937: E/AndroidRuntime(12068):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:792)
03-28 07:40:58.937: E/AndroidRuntime(12068):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:608)
03-28 07:40:58.937: E/AndroidRuntime(12068):    at dalvik.system.NativeStart.main(Native Method)
03-28 07:40:58.937: E/AndroidRuntime(12068): Caused by: java.lang.NullPointerException
03-28 07:40:58.937: E/AndroidRuntime(12068):    at com.xx.yy.myservice.onStartCommand(upload_service.java:42)
03-28 07:40:58.937: E/AndroidRuntime(12068):    at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:2709)
03-28 07:40:58.937: E/AndroidRuntime(12068):    ... 10 more
我的服务目的:上传文件

长按clear all(当我的服务已经启动时,我按clear all)

重要 服务启动后,我长按并清除所有应用程序

更新
当我写时
返回START\u NOT\u STICKY
结束
onstart命令
它不会给出任何错误,但也不会上载文件,我希望它在后台运行,即使我关闭并清除主应用程序。

您无法阻止从app manager或最近的应用程序终止服务

获得NPE异常的原因是
intent
onStartCommand()
中为
null
。从:

如果服务在其进程结束后重新启动,并且之前返回了除
START\u STICKY\u兼容性之外的任何内容,则此值可能为空


onStartCommand()
下检查NPE,并应用空检查或将其放入try块。Android Dalvik可能会停止或终止服务,如果服务
START\u STICKY
使用

@Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return START_STICKY;
    }

它再次由Android Dalvik启动,即使在应用程序关闭后也会运行。

发布您的服务代码,这也是为什么您要在不同的流程中运行服务?我不想在主应用程序关闭时关闭我的服务。因为这个。@Amiya我的服务代码?发布你的服务类code@ErsinGülbahar您的服务不会关闭它将在后台运行,直到您调用stopSelf()或stop(),谢谢您的回答,对此我并不完全理解,很抱歉,我只写了return START_STICKY_兼容性;onstartcommand方法的enf?问题是当服务开始运行时,我长按并清除所有应用程序,我的意思是我认为它已经退出onstartcommand并转到上载asyntask方法,对吗?您好,我再次尝试了START_STICKY_兼容性,但结果是一样的当我编写START_NOT_STICKY时,它没有给出任何错误,我理解问题,但是为什么我清除主应用程序为什么服务被停止?我希望它仍然在后台运行我尝试过,结果是一样的,但当我尝试**开始\不\不\粘**时,它没有给出任何错误,但它也没有上载文件,我希望我的服务不会影响主应用在我的屏幕截图中是否清晰(当我关闭我的应用时,一切正常)如果设备打开或Android Dalvik停止服务,Android Dalvik将启动您的服务一次,但一旦服务启动,它必须无休止地运行,通过重新查看您的代码,您的服务将在您完成上传后完成,而不是连续运行。这就是为什么当您清除应用程序数据时,服务已完成。希望它能解决你的问题。只需使用一个线程继续运行您的服务,该线程会不断检查上载url并上载数据,并在没有url可上载的情况下循环。抱歉,可能我无法正确判断,我的意思是,如果我清除所有(在屏幕截图中)我的服务将发生什么?我想我的应用程序已经关闭了,但这对服务有什么影响?当它试图上传图片时,它被破坏了吗?访问这个链接,同样的问题。谢谢你的评论,但这是同样的问题吗?ı无法使用registerServices如何实现这一点,这个问题是关于小部件接收器的?