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

时间:2014-03-28 05:55:43

标签: android android-service

我在android上写了一个app和service。我的应用程序和服务正在互相说话。即使我按下主页按钮或后退按钮并退出我的应用程序,一切都很好,我的服务仍在运行并完成其工作。 但问题是: 在我手机附带的截图中。当我长按主页按钮有一个关于最近打开的应用程序的布局,如果我按清除所有并删除我的应用程序我的服务正在强制关闭, 我的意思是即使我清除手机上的所有应用程序,我希望我的服务仍在运行。

这是我的代码:

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

我的服务宗旨:文件上传

长按此按钮清除所有这些(我的服务已启动时按清除所有内容) enter image description here

重要 我在服务开始后长按并清除所有应用

更新 when I write 返回START_NOT_STICKY; end of the onstartcommand it does not give any error but it does not upload the file too, I want it run in the background even I close and clear the main app.

2 个答案:

答案 0 :(得分:0)

您无法阻止该服务从应用管理器或最近的应用中终止。

为什么你得到NPE例外是intent null onStartCommand()。来自documentation

  

如果服务在其进程消失后重新启动,则该值可能为null,并且之前已返回除START_STICKY_COMPATIBILITY之外的任何内容

答案 1 :(得分:0)

检查onStartCommand()下的NPE并应用空检查或将它们放入try块中。 Android Dalvik可能会停止或终止服务,如果服务是START_STICKY,则使用

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

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