MADMVX
MADMVX

Reputation: 379

Background Service don't work - Android

I try to run a method in my service every two seconds, but when i start the services just run one time This is the relevant code:

the start service:

 mViewHolder.mLinearLayoutContainer.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            Intent launchIntent = view.getContext().getPackageManager().getLaunchIntentForPackage(mListStorage.get(position).getAdrress());

            mApkPackage = mListStorage.get(position).getAdrress();
            Intent intent = new Intent(view.getContext(), KillerService.class);
            if(mApkPackage != null){
                intent.putExtra("NAMEAPK", mApkPackage);
                view.getContext().startService(new Intent(view.getContext().getApplicationContext(), KillerService.class));
                view.getContext().bindService(intent,mServiceConnection, Context.BIND_AUTO_CREATE);
            }


            if (launchIntent != null) {
                view.getContext().startActivity(launchIntent);//null pointer check in case package name was not found
            }
        }
    });

And this is from my Service class:

@Override
protected void onHandleIntent(@Nullable Intent intent) {
    final Handler handler = new Handler();
    handler.postDelayed(new Runnable() {
        @Override
        public void run() {
            //mAppsNames();
            Log.d("SYSTEMRUNNIGKILLI", "matandoapps");

        }
    }, 2000);
}


@Nullable
@Override
public IBinder onBind(Intent intent) {

    mApkName = intent.getStringExtra("NAMEAPK");
    Log.d("HOLAXD", mApkName);

    return null;
}




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

The part of Log.d("SYSTEMRUNNIGKILLI", "matandoapps"); just run one time and not every 2 seconds.

Upvotes: 0

Views: 91

Answers (2)

Manohar
Manohar

Reputation: 23404

Another way just add handler.postDelayed(this,2000);

 final Handler handler = new Handler();
    handler.postDelayed(new Runnable() {
        @Override
        public void run() {
            //mAppsNames();
            Log.d("SYSTEMRUNNIGKILLI", "matandoapps");

            handler.postDelayed(this,2000);
        }
    }, 2000);

Upvotes: 1

Muhammad Hassaan
Muhammad Hassaan

Reputation: 1017

You are using wrong method to call code after every 2 seconds . Try to use this method

      new Timer().scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {}
        }, 0, 1000); //1000 miliseconds equal to 1 second

Upvotes: 3

Related Questions