在服务中运行ASync任务

时间:2016-01-19 09:22:42

标签: android android-intent

我正在构建一个应用程序,它将检查json中URL的数据并将其显示在UI中。我创建了一个我想运行Async任务的服务。该服务工作正常,运行正常,我只是无法运行任务。有什么想法吗?

public class Getmonitors extends AsyncTask<Void, Void, Void> {

    // Hashmap for ListView
    ArrayList<HashMap<String, String>> monitorList;
    ProgressDialog pDialog;

    @Override
    public void onPreExecute() {
        super.onPreExecute();
        // Showing progress dialog
        pDialog = new ProgressDialog(myActivity.this);
        pDialog.setMessage("Please wait...");
        Log.v(LOG_TAG, "PLEASE WAIT");
        pDialog.setCancelable(false);
        pDialog.show();
    }

    @Override
    public Void doInBackground(Void... arg0) {
        // Creating service handler class instance
        NewWebRequest webreq = new NewWebRequest();

        // Making a request to url and getting response
        String jsonStr = webreq.makeWebServiceCall(url, NewWebRequest.GET);

        monitorList = ParseJSON(jsonStr);

        return null;
    }

    @Override
    public void onPostExecute(Void result) {
        super.onPostExecute(result);
        // Dismiss the progress dialog
        if (pDialog.isShowing())
            pDialog.dismiss();
        /**
         * Updating parsed JSON data into ListView
         * */

     //  Intent intent = new Intent(MainActivity.this, myService.class);
     //            startService(intent);


        ListAdapter adapter = new SimpleAdapter(

                myActivity.this, monitorList,
                R.layout.list_item, new String[]{TAG_NAME, TAG_EMAIL,
                TAG_STATUS}, new int[]{R.id.name,
                R.id.email, R.id.statuslist});

        setListAdapter(adapter);


     //            setContentView(R.layout.activity_main);

        Button button = (Button) findViewById(R.id.button1);

        button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                ImageView iv = (ImageView) findViewById(R.id.imageview1);
                iv.setVisibility(View.VISIBLE);

                new Getmonitors().execute();
                iv.setVisibility(View.INVISIBLE);
            }
        });


        //service onDestroy callback method will be called
        findViewById(R.id.start_service).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(myActivity.this, myService.class);
                startService(intent);
            }
        });


        //service onDestroy callback method will be called
        findViewById(R.id.stop_Service).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(myActivity.this, myService.class);
                stopService(intent);
            }
        });

    }

  }

在服务中:

@Override
public int onStartCommand(final Intent intent, int flags, int startId) {


    //Creating new thread for my service
    //Always write your long running tasks in a separate thread, to avoid ANR
    new Thread(new Runnable() {


        @Override
        public void run() {



            //Your logic that service will perform will be placed here
            //In this example we are just looping and waits for 1000 milliseconds in each loop.
            for (int i = 0; i < 2; i++) {
                try {
                    Thread.sleep(20000);
                } catch (Exception e) {
                }

                if(isRunning) {

                        Log.v("WORKS!!!!!!!!!!!!!!", " url");

                }
            }

            //Stop service once it finishes its task
            stopSelf();
        }
    }).start();

    return Service.START_STICKY;
}

1 个答案:

答案 0 :(得分:0)

这每30秒在另一个任务中运行我的异步任务十次。

主要活动

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

@Override
protected void onResume() {
    super.onResume();
    new Getmonitors().execute();

}


ProgressBar progressBar;

private MyBroadcastReceiver myBroadcastReceiver;
private MyBroadcastReceiver_Update myBroadcastReceiver_Update;

@Override
public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    progressBar = (ProgressBar)findViewById(R.id.progressbar);

    //prepare MyParcelable passing to intentMyIntentService
    String msgToIntentService = "Android-er";



    //Start MyIntentService
    final Intent intentMyIntentService = new Intent(this, MyIntentService.class);
    intentMyIntentService.putExtra(MyIntentService.EXTRA_KEY_IN, msgToIntentService);
    startService(intentMyIntentService);

    myBroadcastReceiver = new MyBroadcastReceiver();
    myBroadcastReceiver_Update = new MyBroadcastReceiver_Update();

    //register BroadcastReceiver
    IntentFilter intentFilter = new IntentFilter(MyIntentService.ACTION_MyIntentService);
    intentFilter.addCategory(Intent.CATEGORY_DEFAULT);
    registerReceiver(myBroadcastReceiver, intentFilter);

    IntentFilter intentFilter_update = new IntentFilter(MyIntentService.ACTION_MyUpdate);
    intentFilter_update.addCategory(Intent.CATEGORY_DEFAULT);
    registerReceiver(myBroadcastReceiver_Update, intentFilter_update);

}

@Override
protected void onDestroy() {
    super.onDestroy();
    //un-register BroadcastReceiver
    unregisterReceiver(myBroadcastReceiver);
    unregisterReceiver(myBroadcastReceiver_Update);
}



public class MyBroadcastReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {


        **new Getmonitors().execute();**
         //this is the async task

        int update = intent.getIntExtra(MyIntentService.EXTRA_KEY_UPDATE, 0);
        progressBar.setProgress(update);

        //un-register BroadcastReceiver
        unregisterReceiver(myBroadcastReceiver);
        unregisterReceiver(myBroadcastReceiver_Update);

        myBroadcastReceiver = new MyBroadcastReceiver();
        myBroadcastReceiver_Update = new MyBroadcastReceiver_Update();

        //register BroadcastReceiver
        IntentFilter intentFilter = new IntentFilter(MyIntentService.ACTION_MyIntentService);
        intentFilter.addCategory(Intent.CATEGORY_DEFAULT);
        registerReceiver(myBroadcastReceiver, intentFilter);

        IntentFilter intentFilter_update = new IntentFilter(MyIntentService.ACTION_MyUpdate);
        intentFilter_update.addCategory(Intent.CATEGORY_DEFAULT);
        registerReceiver(myBroadcastReceiver_Update, intentFilter_update);



    }
}

public class MyBroadcastReceiver_Update extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        int update = intent.getIntExtra(MyIntentService.EXTRA_KEY_UPDATE, 0);
        progressBar.setProgress(update);
    }
}

<强> MyIntentService

public static final String ACTION_MyIntentService = "com.example.androidintentservice.RESPONSE";
public static final String ACTION_MyUpdate = "com.example.androidintentservice.UPDATE";
public static final String EXTRA_KEY_IN = "EXTRA_IN";
public static final String EXTRA_KEY_OUT = "EXTRA_OUT";
public static final String EXTRA_KEY_UPDATE = "EXTRA_UPDATE";
String msgFromActivity;
String extraOut;

public MyIntentService() {
    super("com");
}

@Override
protected void onHandleIntent(Intent intent) {

    //get input
    msgFromActivity = intent.getStringExtra(EXTRA_KEY_IN);
    extraOut = "Hello: " + msgFromActivity;

    for (int x = 0; x <= 10; x++) {

        for (int i = 0; i <= 10; i++) {
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {

                Log.v("loop", "");

                e.printStackTrace();
                Intent intentUpdate = new Intent();
                intentUpdate.setAction(ACTION_MyUpdate);
                intentUpdate.addCategory(Intent.CATEGORY_DEFAULT);
                intentUpdate.putExtra(EXTRA_KEY_UPDATE, i);
                sendBroadcast(intentUpdate);
            }

            //send update
            Intent intentUpdate = new Intent();
            intentUpdate.setAction(ACTION_MyUpdate);
            intentUpdate.addCategory(Intent.CATEGORY_DEFAULT);
            intentUpdate.putExtra(EXTRA_KEY_UPDATE, i);
            sendBroadcast(intentUpdate);
        }

        //return result
        Intent intentResponse = new Intent();
        intentResponse.setAction(ACTION_MyIntentService);
        intentResponse.addCategory(Intent.CATEGORY_DEFAULT);
        intentResponse.putExtra(EXTRA_KEY_OUT, extraOut);
        sendBroadcast(intentResponse);
    }

}