Android暂停服务,线程,Asynctask?使用为此延迟的处理程序?

时间:2016-03-07 12:08:58

标签: android

我有背景服务(Service - > Thread - > Timer - > Asynctask)。 Timer每5秒执行一次Asynctask。如果Asynctask返回true,则发送通知。

现在我希望服务在点击通知后等待20秒(意味着我在接下来的20秒内没有收到另一个通知)。 什么“对象”需要在这里停止?据我所知,暂停Asynctasks不是一个好主意。那么它应该是线程服务还是线程?具有后延迟方法的Handler是最佳解决方案吗?

编辑09.03.2016

public class NotifiyService extends Service {

    String savedsa;
    boolean value;

    protected static final int DEFAULT_TIMEOUT = 5000;
    protected static final int EXTENDED_TIMEOUT = 20000;

    private HandlerThread mBgThread;
    private Handler mBgHandler;
    private MyTimerRunnable mRunnable;


    @Override
    public void onCreate() {
        mBgThread = new HandlerThread("MyBgThread");
        mBgThread.start();
        mBgHandler = new Handler(mBgThread.getLooper(), (Handler.Callback) this);
        mRunnable = new MyTimerRunnable();
    }


    @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();
        mBgHandler.removeCallbacks(mRunnable);
        mBgHandler.postDelayed(mRunnable,EXTENDED_TIMEOUT);
        return START_STICKY;
    }

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

    }

    private class MyTimerRunnable implements Runnable{


        @Override
        public void run() {
            while(!value){
            try {
                URL url = new URL(savedsa);
                HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                httpURLConnection.setRequestMethod("HEAD");
                httpURLConnection.setConnectTimeout(3000);
                httpURLConnection.setReadTimeout(3000);
                httpURLConnection.connect();
                value = true;
            } catch (MalformedURLException e) {
                e.printStackTrace();
                value = false;
            } catch (ProtocolException e) {
                e.printStackTrace();
                value = false;
            } catch (IOException e) {
                e.printStackTrace();
                value = false;
            }

            if(value){
                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());

            }
            mBgHandler.postDelayed(this,DEFAULT_TIMEOUT);}
        }
    }

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

1 个答案:

答案 0 :(得分:1)

如果您已在Thread中产生Service,则无需AsyncTask。您可以使用辅助线程完成所有工作。如果您想使用postDelayed()Handler,请将后台主题设为HandlerThread,并在Handler启动后创建Looper。您可以通过Runnable重新安排相同的postDelayed(),如果您的通知需要更改行为,只需取消现有的Runnable并设置另一个即可在所需的时间范围内运行。

相关问题