应用程序终止后AsyncTask没有得到原谅?
问题描述:
-
我想连续执行一些检查。我已经定义的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);
但是,当我终止应用程序,然后线程停止执行。
答
服务类演示: -
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" />
很明显,它会退出。如果你想运行,那么使用'IntentService'或'Service'来达到这个目的,它将在后台运行。 –
尝试使用服务 –