安排Asynctask - 虽然?服务?计时器?

时间:2016-02-29 15:39:34

标签: android

好的,我有Togglebutton开始service。该服务在Thread中开始新的onStartCommand。在此线程中,执行Asynctask

现在我想要每隔5秒执行一次AsynctaskAsynctask检查网站是否可用。 - >如果没有,5秒后再次检查 - >如果是,请显示消息并停止

使用我现有代码的最佳方法是什么:

public class NotifiyService extends Service {

    String savedsa;
    Thread Th1;
    boolean value;


    final class TheThread implements Runnable{
        int serviceID;
        String savedsa1;
        TheThread(int serviceID,String savedsa){
            this.serviceID = serviceID;
            this.savedsa1 = savedsa;
        }

        @Override
        public void run() {
            HttpTaskParams httpparams = new HttpTaskParams(value,savedsa1);
            new HttpTask().execute(httpparams);
            }
    }
    public NotifiyService() {
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        SharedPreferences sharedPreferences7 = getSharedPreferences("Prefsa",MODE_WORLD_READABLE);
        savedsa = sharedPreferences7.getString("keysa","");
        Toast.makeText(NotifiyService.this,getResources().getString(R.string.MonStarted)+ "\n" + savedsa,Toast.LENGTH_LONG).show();
        Th1 = new Thread(new TheThread(startId,savedsa));
        Th1.start();
        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        //super.onDestroy();
        Toast.makeText(NotifiyService.this,getResources().getString(R.string.MonStopped), Toast.LENGTH_LONG).show();

    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        return null;
    }

    private static class HttpTaskParams{
        boolean value;
        String address;

        HttpTaskParams(boolean value, String address){
            this.value = value;
            this.address = address;
        }

    }

    private class HttpTask extends AsyncTask<HttpTaskParams,Void,Boolean>{

        @Override
        protected Boolean doInBackground(HttpTaskParams... params) {
            boolean value = params[0].value;
            String address = params[0].address;

                try {
                    URL url = new URL(address);
                    HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                    httpURLConnection.setRequestMethod("HEAD");
                    httpURLConnection.setConnectTimeout(3000);
                    httpURLConnection.setReadTimeout(3000);
                    httpURLConnection.connect();
                    value = true;
                    return value;
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                    value = false;
                    return value;
                } catch (IOException e) {
                    e.printStackTrace();
                    value = false;
                    return value;
                }
        }
        @Override
        protected void onPostExecute(Boolean  result) {
            if(result){
                Toast.makeText(NotifiyService.this,"true",Toast.LENGTH_SHORT).show();

                //Notification in Status Bar
                NotificationCompat.Builder builder = new NotificationCompat.Builder(NotifiyService.this);
                builder.setSmallIcon(R.drawable.dummy);
                Intent intent = new Intent(NotifiyService.this, Main2Activity.class);
                intent.setAction(Intent.ACTION_MAIN);
                intent.addCategory(Intent.CATEGORY_LAUNCHER);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                PendingIntent pendingIntent = PendingIntent.getActivity(NotifiyService.this,0,intent,0);
                builder.setContentIntent(pendingIntent);
                builder.setLights(Color.YELLOW,600,600);
                builder.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
                builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.dummy));
                builder.setContentTitle(getResources().getString(R.string.newNotify));
                builder.setContentText(getResources().getString(R.string.newNotify2));
                builder.setAutoCancel(true);
                NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
                notificationManager.notify(1,builder.build());

            }
            else{
                Toast.makeText(NotifiyService.this,"false",Toast.LENGTH_SHORT).show();
            }
        }
    }
}

编辑:

@Override
    public void run() {
            ScheduledExecutorService checkreg = Executors.newScheduledThreadPool(1);
            scheduledFuture = checkreg.scheduleAtFixedRate(new Runnable() {
                @Override
                public void run() {
                    HttpTaskParams httpparams = new HttpTaskParams(value, savedsa1);
                    new HttpTask().execute(httpparams);
                }
            }, 0, 20, TimeUnit.SECONDS);}

@Override
    public void onDestroy() {
        //super.onDestroy();
        Th1.interrupt();
        scheduledFuture.cancel(false);
        Toast.makeText(NotifiyService.this,getResources().getString(R.string.MonStopped), Toast.LENGTH_LONG).show();
        stopSelf();
    }

2 个答案:

答案 0 :(得分:2)

我认为DF %>% mutate(dummy = ifelse(Distractor != "MASK", 0, 1)) %>% ## MASK dashed ## ggplot(aes(x = Lag, y = ., colour = Distractor, group = Distractor, linetype = dummy %>% as.factor())) + guides(linetype = FALSE,color=guide_legend(override.aes=list(linetype=c(1,1,1,2)))) + ## Drop the dummy legend ## geom_line(size = .75) + scale_colour_grey() + theme_classic() + labs(x = "Lag", y = "Probability of T2 report") + ylim(0, 1) 可以帮到你。 请检查this回答。 如果这对你有所帮助,请告诉我。

答案 1 :(得分:1)

试试这个/ **  *定期从网络加载汇率  *返回广播消息中的结果。  *由koss于19.02.16创建。  * * / 公共类EcbEuropeService扩展了服务{

public static final String ECB_URL = "http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml";
public static final int UPDATE_PERIOD = 30000;
public static final int UPDATE_TICK = 1000;

public static final String NOTIFICATION = "koss.ru.oneclickrate.receiver";
public static final String EXTRA_CURRENCIES_MAP = "extra_currencies_map";

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    getUrlData();
    return Service.START_NOT_STICKY;
}

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

public Cubes getUrlData() {
    (new AsyncTask<Object, Object, Cubes>() {
        Map<CurrencyType, BigDecimal> result = new EnumMap<CurrencyType, BigDecimal>(CurrencyType.class);

        @Override
        protected Cubes doInBackground(Object... params) {
            Cubes cubes = new Cubes();
            InputStream is = null;
            HttpURLConnection urlConnection = null;
            try {
                URL url = new URL(ECB_URL);
                urlConnection = (HttpURLConnection) url.openConnection();
                is = urlConnection.getInputStream();
                cubes = EcbEuropeResponseParser.parse(is);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if(urlConnection!=null) IOUtils.close(urlConnection);
                if(is!=null) IOUtils.closeQuietly(is);
                return cubes;
            }
        }

        @Override
        protected void onPostExecute(Cubes map) {
            super.onPostExecute(map);
            sendBroadcastMessage(map);
            startTimer();
        }
    }).execute();
    return null;
}

/**
 * Restarts timer
 * */
public void startTimer() {
    cdt.cancel();
    cdt.start();
}

CountDownTimer cdt = new CountDownTimer(UPDATE_PERIOD, UPDATE_TICK) {
    @Override
    public void onTick(long millisUntilFinished) {

    }

    public void onFinish() {
        getUrlData();
    }
};

private void sendBroadcastMessage(Cubes currenciesMap) {
    Intent intent = new Intent(NOTIFICATION);
    intent.putExtra(EXTRA_CURRENCIES_MAP, currenciesMap);
    sendBroadcast(intent);
}

}