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.
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
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);
Related
So I have this code, that has a countdown timer in a service with a 10 second timer. What I want to do is in the onFinish() method I want to launch the Activity (which is called MainActivity) automatically even when I am outside the app.
public class TimeDisplayTimerTask extends TimerTask{
CountDownTimer timer;
NotificationCompat.Builder notification;
private static final String TAG="com.timer";
private Handler mHandler = new Handler();
#Override
public void run() {
// run on another thread
mHandler.post(new Runnable() {
#Override
public void run() {
// display toast
timer = new CountDownTimer(10000, 1000) {
#Override
public void onFinish(){
}
#Override
public void onTick(long millisUntilFinished) {
Log.i(TAG,"" + millisUntilFinished/1000);
}
};
timer.start();
}
});
}
}
Try This to open your main activty after 10 second.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
// launch your main activity here and finish your current activity
}
}, 10000);
}
Probably you will have to override lifecycle method's and also use PARTIAL_WAKE_LOCK to keep cpu running untill you finish execution, in case user lock screen.
If you are inside a service then simply launch you activity using intent. Put this code in your onFinish() method:
Intent i = new Intent();
i.setClass(this, MainActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
You neet to pass an activity context to your TimeDisplayTimerTask :
public class TimeDisplayTimerTask extends TimerTask{
CountDownTimer timer;
NotificationCompat.Builder notification;
private static final String TAG="com.timer";
private Handler mHandler = new Handler();
private Activity mActivity;
public TimeDisplayTimerTask(Activity activity){
mActivity = activity;
super();
}
#Override
public void run() {
// run on another thread
mHandler.post(new Runnable() {
#Override
public void run() {
// display toast
timer = new CountDownTimer(10000, 1000) {
#Override
public void onFinish(){
if (activity != null {
Intent startIntent = new Intent(activity, MainActivity.class);
startIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
activity.startActivity(startIntent);
}
}
#Override
public void onTick(long millisUntilFinished) {
Log.i(TAG,"" + millisUntilFinished/1000);
}
};
timer.start();
}
});
}
}
I am developing an application in which I want to implement timer task to print a toast message every 5 seconds. The problem is my application crashes after 5 seconds when i run it.Below is part of my code please tell me where I am making mistakes and how can I overcome it.
public class main_activity extends Activity implements BluetoothLeUart.Callback{
public ImageButton fabbutton;
Activity activity;
Timer time;
TimerTask timetask;
Handler handle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_activity);
fabbutton = (ImageButton) findViewById(R.id.fabbutton);
startTimer(); //this is where I start my timer task
fabbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
scanLeDevice(false);
Intent intent = new Intent(getApplicationContext(), ScanList.class);
startActivity(intent);
}
});
}
public void startTimer(){
time = new Timer();
initializeTimerTask();
time.schedule(timetask, 5000, 10000);
}
public void initializeTimerTask(){
timetask = new TimerTask() {
#Override
public void run() {
handle.post(new Runnable() {
#Override
public void run() {
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(getApplicationContext(),"Timer...", duration);
toast.show();
}
});
}
};
}
public void stoptimertask() {
//stop the timer, if it's not already null
if (time != null) {
time.cancel();
time = null;
}
}
}
you forgot to initialize handler,
Just add below line in oncreate or startTimer();
handle = new Handler();
Or even in your case you can use,
runOnUiThread(new Runnable(){
#Override
public void run() {
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(getApplicationContext(),"Timer...", duration);
toast.show();
}
});
I'm new to android and i have a problem
I used same code to repeat and delay method for two class. One class work fine but other not. I don't know why. This is my code
SpeedMeterFragment.java
public class SpeedMeterFragment extends Fragment {
....
public void speedMeterBefore() {
totalRxBytesBefore = TrafficStats.getTotalRxBytes();
Log.d("test", "Before: " + String.valueOf(totalRxBytesBefore));
}
public void speedMeterAfter() {
totalRxBytesAfter = TrafficStats.getTotalRxBytes();
Log.d("test", "After: " + String.valueOf(totalRxBytesAfter));
}
public void speedMeterDifference() {
totalRxBytesDifference = totalRxBytesAfter - totalRxBytesBefore;
tvTest.setText(String.valueOf(totalRxBytesDifference/1024) + " kb/s");
Log.d("test", "Difference: " + String.valueOf(totalRxBytesDifference));
}
public void speedMeter() {
handler = new Handler();
handler.post(runnable = new Runnable() {
#Override
public void run() {
speedMeterBefore();
final Handler handler1 = new Handler();
handler1.postDelayed(new Runnable() {
#Override
public void run() {
speedMeterAfter();
speedMeterDifference();
}
}, 1000);
handler.postDelayed(this, 1000);
}
});
}
}
and SaveDataUseage.java
public class SaveDataUseage extends BroadcastReceiver {
...
public void onReceive(Context context, Intent intent) {
...
savePreference();
}
public void savePreference() {
...
measureDataMB();
}
public void measureDataMBBefore() {
dataMBBefore = TrafficStats.getTotalRxBytes() / 1048576;
}
public void measureDataMBAfter() {
dataMBAfter = TrafficStats.getTotalRxBytes() / 1048576;
}
public void measureDataMBDifference() {
dataMBDifference = dataMBAfter - dataMBBefore;
}
public void measureDataMB() {
handler = new Handler();
handler.post(runnable = new Runnable() {
#Override
public void run() {
measureDataMBBefore();
final Handler handler1 = new Handler();
handler1.postDelayed(new Runnable() {
#Override
public void run() {
measureDataMBAfter();
measureDataMBDifference();
}
}, 1000);
handler.postDelayed(this, 1000);
}
});
}
}
SpeedMeterFragment work fine, but not SaveDataUseage
Anybody help me?
Sorry for my bad English :)
handler = new Handler();
final Runnable r = new Runnable() {
public void run() {
//Your method called here
handler.postDelayed(this, 1000);
}
};
handler.postDelayed(r, 1000);
this code will repeat method after every second
handler = new Handler();
final Runnable r = new Runnable() {
public void run() {
//Your method called here
MyMethod(isCalledFromHandeler);
handler.postDelayed(this, 1000);
}
};
handler.postDelayed(r, 1000);
use boolean argument isCalledFromHandeler to recognition the caller of method.
and then use
if(isCalledFromHandeler){
// Do Not call the Child Method
} else{
// Call the Child Method
}
Although its eight month old question, I also faced the similar problem and in solution I extended Handler class to AdvanceHandler with the postRepeated method.
Sample Usage
AdvanceHandler handler = new AdvanceHandler();
handler.postRepeated(new Runnable() {
#Override
public void run() {
//Your repeated task
}
}, 5000) //After every 5 seconds
I use it to call another activity
Main.java
Intent intent = new Intent(this, Message_Note.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
Message_Note.java :
public class Message_Note extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.message);
}
}
How can i CLOSE the Message_Note Activity after 10 seconds ?? i should use a thread ?
After 100 MS, the activity will finish using the following code.
public class Message_Note extends Activity
{
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.message);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
finish();
}
}, 100);
}
}
You can use following approach.
Approach 1
int finishTime = 10; //10 secs
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
YourActivity.this.finish();
}
}, finishTime * 1000);
Approach 2
int FinishTime = 10;
int countDownInterval = 1000;
counterTimer = new CountDownTimer(FinishTime * 1000, countDownInterval) {
public void onFinish() {
//finish your activity here
}
public void onTick(long millisUntilFinished) {
//called every 1 sec coz countDownInterval = 1000 (1 sec)
}
};
counterTimer.start();
You can use AlarmManager. See :
http://developer.android.com/reference/android/app/AlarmManager.html
and
Alarm Manager Example
Another way is just like this:
new Handler().postDelayed(new Runnable(){
#Override
public void run() {
Message_Note.this.finish();
}
}, 10000);
I am creating an app that vibrate and beep every 30 sec and when I log out the vibrate and beep must be cancelled and when I log in the vibrate and beep should resume.
NOTE: it must vibrate and beep for every 30 sec until I log out
In my app I am using TimerTask for this implementation
this is the code for vibrate and beep using TimerTask
static TimerTask Task;
final static Handler handler = new Handler();
static Timer t = new Timer();
public static void vib() {
Task = new TimerTask() {
public void run() {
handler.post(new Runnable() {
public void run() {
Vibrator vibrator = (Vibrator) ApplicationUtils.getContext().getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(3000);
playSound();
Log.d("TIMER", "Timer set on");
}
});
}
};
t.schedule(Task, 0, 30000);
}
This is the code I'm using in logout section
public void stopvib() {
if (Task != null) {
// Log.d("TIMER", "timer canceled");
t.cancel();
Task.cancel();
}
}
Note: I also removed the Task.cancel(); but still I am getting same error
My vibrate working fine before logout and again login I am geting error
java.lang.IllegalStateException: Timer was cancelled
at java.util.Timer.scheduleImpl(Timer.java:562)
at java.util.Timer.schedule(Timer.java:481)
at com.vib(AlertListActivity.java:724)
can any one help me with this coding. Where did I go wrong?
i have recently run this code and is working fine. This can be achieved using broadcast Receiver.You have to implement separate CustomTimer task that extend TimerTask:
Activity mActivity=null;
public MyCustomTimer(Activity mActivity) {
this.mActivity=mActivity;
}
#Override
public void run() {
this.mActivity.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(mActivity, "Write you code here",Toast.LENGTH_LONG).show();
Log.d("MyCustomTimer","Call");
}
});
}
After this you have to implement BroadCast Receive in that class where you want to implement " vib() " method.:
Let say, in my case (just for example ) is MainActivity:
public class MainActivity extends Activity {
private MyCustomTimer myCustomTimer = null;
BroadcastReceiver mBr_Start = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("START_VIBRATION")) {
System.out.println("onreceive :START_VIBRATION");
vib();
}
}
};
BroadcastReceiver mBr_Stop = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("STOP_VIBRATION")) {
stopVibration();
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
IntentFilter mIntentFilter = new IntentFilter();
mIntentFilter.addAction("START_VIBRATION");
registerReceiver(mBr_Start, mIntentFilter);
IntentFilter mIntentFilter2 = new IntentFilter();
mIntentFilter2.addAction("STOP_VIBRATION");
registerReceiver(mBr_Stop, mIntentFilter2);
Button b1 = (Button) findViewById(R.id.button1);
b1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MainActivity.this, MySecondActivity.class)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
private void vib() {
myCustomTimer = new MyCustomTimer(MainActivity.this);
Timer timer = new Timer();
timer.scheduleAtFixedRate(myCustomTimer, 0, 30000);
}
private void stopVibration() {
Log.d("MainActivity", "Before Cancel");
if (null != myCustomTimer)
myCustomTimer.cancel();
Log.d("MainActivity", "After Cancel");
}
}
Now,you can start Or stop vibration by implementing these lines:
To start vibration:
Intent i=new Intent("START_VIBRATION");
mActivity.sendBroadcast(i);
To Stop:
Intent i=new Intent("STOP_VIBRATION");
mActivity.sendBroadcast(i);
Note:
onDestroy() of MainActivity (in your case,Where you implement Broadcast Receiver,unregister BroadcastReceiver.)
Set timer instance to null when you logout and then initialize it everytime user logged in the app. This will fix the "Timer was cancelled" related issues.
Why do you need a static TimerTask.You can give like this which works fine for me.
timer.schedule(new TimerTask() {
#Override
public void run() {
//your code
}
}, 0, 30000);
While logout use, timer.cancel().
Here you can simply cancel the timer.No need to cancel the TimerTask.