从asynctask启动服务时的应用程序块

时间:2013-06-11 12:39:40

标签: android

我从onPostExecute()方法中的asynctask启动服务。然后它阻止了UI和应用程序。我正在服务中执行网络操作。

请建议我在onPostExecute中从Asynctask启动服务。

提前致谢。

package com.homebulletin;

import java.io.File;
import java.io.FileOutputStream;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.Environment;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

/**
 * Service which check the any updates found on the server.
 * @author Ajay
 */

public class MainService extends Service {

    private Context context;
    private String buildPath;

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

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        //Get the installed application version Code.
        try {
            context = this;
            PackageManager packageManager = this.getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(this.getPackageName(), 0);
            String installedVersionCode = packageInfo.versionName;
            String serverResponse = null;
            String serverBuildVersionCode = null;

            //Fetch the user credentials
            String userCredentials[] = new Util().getUserCredentials(context);

            //Checking internet connection and sending request to server
            try {
                ConnectivityManager conMan = ( ConnectivityManager ) getSystemService( Context.CONNECTIVITY_SERVICE );
                if(conMan.getActiveNetworkInfo() != null && conMan.getActiveNetworkInfo().isConnected()) {
                    serverResponse = new Connection().getResponse(GlobalVars.localServerURL, userCredentials[0], userCredentials[1]);
                }
            } catch(Exception e) {
                try {
                    serverResponse = new Connection().getResponse(GlobalVars.remoteServerURL, userCredentials[0], userCredentials[1]);
                } catch (Exception e1) { }
            }

            serverBuildVersionCode = new Util().parseXML(serverResponse, "SERVER", "version");
            buildPath = new Util().parseXML(serverResponse, "SERVER", "apkpath");

            //True if updated build found on server
            if(serverBuildVersionCode != null && (Float.parseFloat(installedVersionCode) <= Float.parseFloat(serverBuildVersionCode))) {
                downloadAPKOnSDCard();
                new ViewNotification("Home Bulletin", "Update Version is available", 1, android.R.drawable.stat_sys_warning, context, installApplication()).showNotification();
            }
        } catch(Exception e) {
            Log.v("Home Bulletin", "Exception at::" + e.getMessage());
        }
        return START_STICKY;
    }

    /**
     * Download new build (APK) on mobile SDCard.
     */
    private void downloadAPKOnSDCard() {
        DefaultHttpClient httpClient = null;
        try {
            httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(buildPath);
            HttpResponse response = httpClient.execute(httpPost);

            if(response.getStatusLine().getStatusCode() == 200) {
                boolean isSdCardMounted = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED); //Checking SD card mounted or not.
                if(isSdCardMounted) {
                    String PATH = Environment.getExternalStorageDirectory() + "/download/";
                    File file = new File(PATH);
                    if(!file.exists())
                        file.mkdirs();
                    File outputFile = new File(file, "entcon.apk");
                    FileOutputStream fileOutStream = new FileOutputStream(outputFile);
                    response.getEntity().writeTo(fileOutStream);
                } else {
                    Toast.makeText(context, getString(R.string.insert_sd_card), Toast.LENGTH_LONG).show();
                }
            }
        }
        catch(Exception e) {
            Log.v("Home Bulletin", "Exception while create connection for download at: " + e.getMessage());
        }
        finally {
            httpClient.getConnectionManager().shutdown();
        }
    }

    /**
     * Install the specific package name (application).
     */
    private Intent installApplication() {
        Uri packageURI = Uri.parse("package:" + "com.homebulletin");
        Intent intent = new Intent(android.content.Intent.ACTION_VIEW, packageURI);
        intent.setDataAndType(Uri.fromFile(new File(Environment.getExternalStorageDirectory() + "/download/entcon.apk")), "application/vnd.android.package-archive");
        return intent;
    }
}


@Override
        protected void onPostExecute(Void param) {
            progressDialog.cancel();
            try {
                if(result != null) {

                    /** Parsing XML */
                    XMLParser parser = new XMLParser();
                    Document doc = parser.getDomElement(result);
                    if(doc != null)
                    {
                        NodeList nodeList = doc.getElementsByTagName("usersettings");

                        if(nodeList.getLength() > 0) {
                            NodeList nodeModuleList = doc.getElementsByTagName("module");

                            for(int i = 0; i < nodeModuleList.getLength(); i++) {
                                Element element = (Element) nodeModuleList.item(i);

                                String keyName = element.getAttribute("key");

                                if(keyName.equalsIgnoreCase("LOG")) {

                                    NodeList propertyNodeList = doc.getElementsByTagName("property");
                                    for(int j = 0; j < propertyNodeList.getLength(); j++) {
                                        Element propertyElement = (Element) propertyNodeList.item(j);
                                        String propertyName = propertyElement.getAttribute("name");
                                        if(propertyName.equalsIgnoreCase("login_success")) {
                                            String propertyValue = propertyElement.getAttribute("value");
                                            if(propertyValue.equalsIgnoreCase("1")) {

                                                //Save the XML to internal storage of device.
                                                boolean isSaved = new Util().saveXMLToInternalStorage(result, context, username + ".xml");

                                                if(isSaved) {
                                                    Toast.makeText(context, getString(R.string.user_login_success), Toast.LENGTH_LONG).show();
                                                    //Saving data in shared preference.
                                                    SharedPreferences sharedPreferences = context.getSharedPreferences("user_details", MODE_PRIVATE);
                                                    Editor editor = sharedPreferences.edit();
                                                    editor.putString("isLogin", "true");
                                                    editor.putString("userid", username);
                                                    editor.putString("password", password);
                                                    editor.commit();
                                                    finish();
                                                    startActivity(new Intent(context, HomeBulletinMainActivity.class));
                                                    new Util().startAlarmManager(context);
                                                    break;
                                                } else {
                                                    Toast.makeText(context, getString(R.string.something_went_wrong), Toast.LENGTH_LONG).show();
                                                }
                                            }
                                            else
                                                Toast.makeText(context, getString(R.string.user_can_not_login), Toast.LENGTH_LONG).show();
                                        }
                                    }
                                }
                            }
                        }
                    }
                } else if(result == null) {
                    Toast.makeText(context, getString(R.string.time_out), Toast.LENGTH_LONG).show();
                }
            } catch(Exception e) {
                Toast.makeText(context, getString(R.string.time_out), Toast.LENGTH_LONG).show();
            }
        }

2 个答案:

答案 0 :(得分:0)

  

我正在服务中执行网络操作。

这是Android的工作方式。如果你真的想在服务中执行网络任务,可以考虑使用IntentService.It在后台线程上执行所有任务,这样就不会阻止UI。

我已经发布了一个代码片段,显示了行动中的IntentService

how to create own download manager in android 2.2

答案 1 :(得分:0)

所有进程都在asynctask的boInBackground()中进行。不要在onPostExecute()方法中加载。 请参阅link