2016-04-25 47 views
0
  1. 我想連續執行一些檢查。我已經定義的AsyncTask爲 如下,應用程序終止後AsyncTask沒有得到原諒?

     new AsyncTask<String, Void, String>() { 
    
            @Override 
            protected void onPreExecute() { 
             Log.d(TAG, "onPreExecute()"); 
            } 
    
            @Override 
            protected String doInBackground(String... params) { 
             sendData(array); 
             return null; 
            } 
    
            @Override 
            protected void onPostExecute(String res) {     } 
           }.execute(userResponse); 
    

但是,當我終止應用程序,然後線程停止執行。

+4

很明顯,它會退出。如果你想運行,那麼使用'IntentService'或'Service'來達到這個目的,它將在後臺運行。 –

+0

嘗試使用服務 –

回答

1

服務類演示: -

package com.example.My Application; 

import android.app.Service; 
import android.content.Intent; 
import android.os.IBinder; 
import android.widget.Toast; 

public class MyService extends Service { 

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

    @Override 
    public int onStartCommand(Intent intent, int flags, int startId) { 
     // Let it continue running until it is stopped. 
     Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show(); 
     return START_STICKY; 
    } 

    @Override 
    public void onDestroy() { 
     super.onDestroy(); 
     Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show(); 
    } 
} 

活動: -

package com.example.My Application; 

import android.os.Bundle; 
import android.app.Activity; 
import android.view.Menu; 
import android.content.Intent; 
import android.view.View; 

public class MainActivity extends Activity { 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
    } 

    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     getMenuInflater().inflate(R.menu.activity_main, menu); 
     return true; 
    } 

    // Method to start the service 
    public void startService(View view) { 
     startService(new Intent(getBaseContext(), MyService.class)); 
    } 

    // Method to stop the service 
    public void stopService(View view) { 
     stopService(new Intent(getBaseContext(), MyService.class)); 
    } 
} 

清單: -

添加<service android:name=".MyService" />