如何将asyncTask更改为服务?

时间:2016-10-31 10:33:30

标签: android service android-asynctask android-wallpaper

如何将asyncTask更改为服务,因为每次关闭应用程序或重启设备时,我的aysncTask都无法正常工作。 我有一个发送Post请求到php服务器的aysnc,我在每个请求上都找到了一个图像所以我把设置选项给用户他可以选择每隔1,5,10改变壁纸的图片,..... min但是就像我说我想要服务所以当用户选择更改壁纸的时机并关闭(销毁)应用程序服务器仍然计算在这里更改是我的代码

public class MainActivity extends AppCompatActivity {

    TextView txt;
    Button btn;
    String forecastJsonStr;
    RadioButton rd1, rd2, rd3, rd4, rd5, rd6, rd7;
    Handler mHandler;
    RadioGroup radioGroup;

    private final static int INTERVAL = 1000*60 * 1; //1 min
    private final static int INTERVAL2 = 1000*60*5; // 5 min
    private final static int INTERVAL3 = 1000 * 60 * 10; // 10 min
    private final static int INTERVAL4 = 1000 * 60 * 15; // 15 min
    private final static int INTERVAL5 = 1000 * 60 * 30; // 30 min
    private final static int INTERVAL6 = 1000 * 60 * 60; // 1 hour
    private final static int INTERVAL7 = 1000 * 60 * 1440; // 1 day

    private final String hostName = "http://555.555.555.555";
    private final String hostRequestName = "/yay.php";
    private final String hostWallpaperName = "/wallpaper/";
    private static int SELECTED_INTERVAL = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        txt = (TextView) findViewById(R.id.textView);
        rd1 = (RadioButton) findViewById(R.id.radioButton);
        rd2 = (RadioButton) findViewById(R.id.radioButton2);
        rd3 = (RadioButton) findViewById(R.id.radioButton3);
        rd4 = (RadioButton) findViewById(R.id.radioButton4);
        rd5 = (RadioButton) findViewById(R.id.radioButton5);
        rd6 = (RadioButton) findViewById(R.id.radioButton6);
        rd7 = (RadioButton) findViewById(R.id.radioButton7);
        radioGroup = (RadioGroup) findViewById(R.id.radiogroup);
        mHandler = new Handler();
        btn = (Button) findViewById(R.id.button);

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(rd1.isChecked()) {
                    SELECTED_INTERVAL = INTERVAL;
                } else if (rd2.isChecked()) {
                    SELECTED_INTERVAL = INTERVAL2;
                }
                startRepeatingTask();
            }
        });
    }

    void startRepeatingTask() {
        mHandlerTask.run();
    }

    Runnable  mHandlerTask = new Runnable() {
        @Override
        public void run() {
            new WallpaperData().execute();
            mHandler.postDelayed(mHandlerTask, SELECTED_INTERVAL);
        }
    };

    private class WallpaperData extends AsyncTask<Void, Void, String> {

        @Override
        protected String doInBackground(Void... params) {

            HttpURLConnection urlConnection = null;
            BufferedReader reader = null;

            try {

                URL url = new URL("http://555.555.555.555/yay.php");

                urlConnection = (HttpURLConnection) url.openConnection();
                urlConnection.setRequestMethod("POST");
                urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                urlConnection.setDoInput(true);
                urlConnection.setDoOutput(true);
                urlConnection.connect();
                DataOutputStream wr = new DataOutputStream(
                        urlConnection.getOutputStream());
                wr.write("method=get_random_wallpaper".getBytes());
                wr.flush();
                wr.close();

                InputStream inputStream = urlConnection.getInputStream();
                StringBuffer buffer = new StringBuffer();
                if (inputStream == null) {
                    return null;
                }
                reader = new BufferedReader(new InputStreamReader(inputStream));

                String line;
                while ((line = reader.readLine()) != null) {
                    buffer.append(line + "\n");
                    Log.d("hey", buffer.toString());
                }

                if (buffer.length() == 0) {
                    return null;
                }
                forecastJsonStr = buffer.toString();

                return forecastJsonStr;
            } catch (IOException e) {
                Log.e("PlaceholderFragment", "Error ", e);
                return null;
            } finally {
                if (urlConnection != null) {
                    urlConnection.disconnect();
                }
                if (reader != null) {
                    try {
                        reader.close();
                    } catch (final IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }

        @Override
        protected void onPostExecute(final String forecastJsonStr) {

            txt.setText(forecastJsonStr);

            Thread thread = new Thread(new Runnable() {

                @Override
                public void run() {

                    WallpaperManager wallpaperManager = WallpaperManager.getInstance(getApplicationContext());
                    try {
                        Bitmap result = Picasso.with(getBaseContext())
                                .load(hostName + hostWallpaperName + forecastJsonStr)
                                .get();
                        wallpaperManager.setBitmap(result);
                    } catch (IOException ex) {
                        ex.printStackTrace();
                    }
                }
            });
            thread.start();

            super.onPostExecute(forecastJsonStr);

        }
    }

}

1 个答案:

答案 0 :(得分:0)

对于大于30秒的时间间隔,您应该使用AlarmManager而不是Handler的.postDelayed方法。请参阅以下教程:https://developer.android.com/training/scheduling/alarms.htmlhttp://code4reference.com/2012/07/tutorial-on-android-alarmmanager/。有一个用于安排重复任务的JonScheduler,Vogella有关于它的教程:http://www.vogella.com/tutorials/AndroidTaskScheduling/article.html。 简而言之:您创建Service(InteneService),创建PendingIntent,指向该服务并安排AlarmManager,它将发送该意图,而这反过来又将启动您的IntentService。