I am calling one webservice in home page in that i will send all the details in that this process is working in bacground. when i come to this home page again i want to know prvious AsyncTask is end or not
what iam doing exactly here
public void callAsynchronousTask() {
//http://stackoverflow.com/questions/6531950/how-to-execute-async-task-repeatedly-after-fixed-time-intervals
final Handler handler = new Handler();
Timer timer = new Timer();
doAsynchronousTask = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
public void run() {
try {
if (vist != null && saves != null && prof != null && semail != null) {
if (vist.getStatus() != AsyncTask.Status.RUNNING) {
if (saves.getStatus() == AsyncTask.Status.PENDING || saves.getStatus() == AsyncTask.Status.FINISHED && saves.getStatus() != AsyncTask.Status.RUNNING)
{
if (prof.getStatus() == AsyncTask.Status.PENDING || prof.getStatus() == AsyncTask.Status.FINISHED && prof.getStatus() != AsyncTask.Status.RUNNING)
{
if (semail.getStatus() == AsyncTask.Status.PENDING || semail.getStatus() == AsyncTask.Status.FINISHED && semail.getStatus() != AsyncTask.Status.RUNNING)
{
checkandsave();
}
}
}
}
} else {
checkandsave();
}
public void checkandsave(){
ConnectionDetector cd = new ConnectionDetector(Home_page.this);
Boolean isInternetPresent = cd.isConnectingToInternet();
if (isInternetPresent) {
DatabaseToadd da = new DatabaseToadd(Home_page.this);
mu = new ArrayList<>();
mu = da.getAllUser();
if (mu.size() > 0) {
vist = new Getvisiterid();
saves=new SaveVisitor();
semail=new sendemail();
prof=new saveprofpic();
vist.executeOnExecutor(THREAD_POOL_EXECUTOR);
}
}
else {
System.out.println("null db");
}
but in this when i come back to this actvity if asynctask running in background then also its showing null if i create object on top its showing pending
Based on your text I'm making the assumption you only need this task run in this activity, and dont need multiple tasks run at once. If this is the case use an asynctaskloader. The asynctask is tied to the lifecycle of the activity and you receive callbacks when it is starting, running in background, and done.
AsyncTaskLoader basic example. (Android)
Related
My requirements are to poll a web service every fixed interval. After instantiating the handler as a private field of the class, I'm doing this in the onCreate method of the main activity:
if (handler != null) {
handler.post(new Runnable() {
#Override
public void run() {
String sessionId = SharedPreferencesHelper.getSessionId(MainActivity.this);
if (sessionId != null && !sessionId.isEmpty()) {
if (Utils.isNetworkAvailable(MainActivity.this)) {
restHandler.getUnreadMessages(sessionId);
}
handler.postDelayed(this, Constants.CHAT_POLLING_REFRESH_DELAY);
} else {
handler.removeCallbacks(this);
}
}
});
}
Then onDestroy:
if (handler != null) {
handler.removeCallbacksAndMessages(null);
handler = null;
}
The backend is complaing that sometimes the sessionId passed is empty or null. How can this be possible? I'm using retrofit. Bonus question: can I have problems with MainActivity.this context reference when app goes in background?
I m facing issue in fitness app after 1 hr timertask runs slow or sometimes it runs too fast like it increase 2 second simantaneously please someone suggest stable solution ..I am saving user history when ever I get new location any help is appreciated
public void reStartTimerTask(final boolean onCreate) {
if (Validator.isNull(timer)) {
if (preferences.isGps()) {
IntentFilter intentFilter = new IntentFilter(Util.LOCAL_RECEIVER);
intentFilter.addCategory(Intent.CATEGORY_DEFAULT);
workoutReceiver = new WorkoutReceiver();
registerReceiver(workoutReceiver, intentFilter);
if (!onCreate) {
if (!Util.isGPSEnabled(this)) {
displayGPSAlert();
}
if (!preferences.isTryOut()) {
Request.getRequest().sendRequest(Request.GET_ALL_TRACE_USER, this, this, RequestParameterBuilder.buildMapForUserId(this));
}
}
}
timer = new Timer();
TimerTask task = new TimerTask() {
#Override
public void run() {
if (preferences.isGps()) {
WorkoutServiceHelper.getWorkoutServiceHelper(MainActivity.this).connect();
}
if (!preferences.isWorkoutPaused()) {
history.duration++;
history.calories = HWUtil.calculateCalorie(history, MainActivity.this);
history.cascadeSave();
}
if (history.duration % 5 == 0 && preferences.isTrace() && !preferences.isRequestSent()) {
//Sync record every five second
UserHistoryModel historyModel = history.loadAll();
if (Validator.isNotNull(historyModel)) {
UserHistory uh = convertUserHistoryModelToUserHistory(historyModel);
/*
don't set history pictures when tracing
*/
uh.setHistoryPictures(null);
uh.setId(uh.getUniqueId());
preferences.setRequestSent(true);
Request.getRequest().sendJsonRequest(Request.ADD_USER_HISTORY, MainActivity.this, MainActivity.this, RequestParameterBuilder.buildJsonObjectFromUserHistory(uh));
}
}
runOnUiThread(new Runnable() {
#Override
public void run() {
if (getSupportFragmentManager().findFragmentByTag(TabFragment.class.getName()) != null) {
TabFragment tabFragment = (TabFragment) getSupportFragmentManager().findFragmentByTag(TabFragment.class.getName());
if (tabFragment.getCurrentFragment() instanceof UpdateListener) {
((UpdateListener) tabFragment.getCurrentFragment()).update();
}
} else if (getSupportFragmentManager().findFragmentByTag(FullMapFragment.class.getName()) != null) {
FullMapFragment mapFragment = (FullMapFragment) getSupportFragmentManager().findFragmentByTag(FullMapFragment.class.getName());
mapFragment.update();
}
}
});
}
};
timer.scheduleAtFixedRate(task, 0, 1000);
}
}
whenever user starts any workout/after pause i m calling this method
I need a little help to get an idea of how to refactor my code, but I can't see options besides what's done, I would like to add the objects but not using so many lists (and if's conditions).
Here is my code, if anyone could help, I appreciate. Thanks
#ViewById
BannerHomeViewPager place1, place2, place3, place4, place5, place6, place7,
place8, place9;
The lists:
private List<HomeItem> allHomeItems = new ArrayList<HomeItem>(),
placeItems1 = new ArrayList<HomeItem>(),
placeItems2 = new ArrayList<HomeItem>(),
placeItems3 = new ArrayList<HomeItem>(),
placeItems4 = new ArrayList<HomeItem>(),
placeItems5 = new ArrayList<HomeItem>(),
placeItems6 = new ArrayList<HomeItem>(),
placeItems7 = new ArrayList<HomeItem>(),
placeItems8 = new ArrayList<HomeItem>(),
placeItems9 = new ArrayList<HomeItem>();
1) Items mocked, ok.
2)
#UiThread
void updateUI() {
if (allHomeItems != null && allHomeItems.size() > 0) {
for (HomeItem item : allHomeItems) {
if (item.getPlacement().contains("1")) {
placeItems1.add(item);
} else if (item.getPlacement().contains("2")) {
placeItems2.add(item);
} else if (item.getPlacement().contains("3")) {
placeItems3.add(item);
} else if (item.getPlacement().contains("4")) {
placeItems4.add(item);
} else if (item.getPlacement().contains("5")) {
placeItems5.add(item);
} else if (item.getPlacement().contains("6")) {
placeItems6.add(item);
} else if (item.getPlacement().contains("7")) {
placeItems7.add(item);
} else if (item.getPlacement().contains("8")) {
placeItems8.add(item);
} else {
placeItems9.add(item);
}
}
}
setupAdapters();
}
3) setupAdapters()
private void setupAdapters() {
if (place1 != null)
place1.update(placeItems1);
if (place2 != null)
place2.update(placeItems2);
if (place3 != null)
place3.update(placeItems3);
if (place4 != null)
place4.update(placeItems4);
if (place5 != null)
place5.update(placeItems5);
if (place6 != null)
place6.update(placeItems6);
if (place7 != null)
place7.update(placeItems7);
if (place8 != null)
place8.update(placeItems8);
if (place9 != null)
place9.update(placeItems9);
}
As #DanielBo answer:
private Map<String, ArrayList<HomeItem>> placeItems = new HashMap<String,ArrayList<HomeItem>>();
void updateUI() {
if (allHomeItems != null && allHomeItems.size() > 0) {
for (HomeItem item : allHomeItems) {
if(!placeItems.containsKey(item.getPlacement())){
placeItems.put(item.getPlacement(), new ArrayList<HomeItem>());
}
placeItems.get(item.getPlacement()).add(item);
}
}
setupAdapters();
}
But why are you using so many views? I really can't say if this is correct bcs i don't know the purpose of this, but I can't figure a good use to so many list views in the same layout...
I want to get launch time of all apps in android. Please suggest me any solution to achieve this. I am using this code. It is to kill non system apps. But it is also not working. Can anybody suggest any solution for it. Thanks
timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
List<RunningAppProcessInfo> appProcesses= activityManager.getRunningAppProcesses();
for (RunningAppProcessInfo appProcess : appProcesses) {
try {
if (appProcess.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
if (!lastFrontAppPkg.equals((String) appProcess.pkgList[0])) {
apkInfo = ApkInfo.getInfoFromPackageName(appProcess.pkgList[0], mContext);
if (apkInfo == null || (apkInfo.getP().applicationInfo.flags && ApplicationInfo.FLAG_SYSTEM) == 1) {
// System app continue;
} else if (((apkInfo.getP().versionName == null)) || (apkInfo.getP().requestedPermissions == null)) {
//Application that comes preloaded with the device
continue;
} else {
lastFrontAppPkg = (String) appProcess.pkgList[0];
}
//kill the app
//Here do the pupop with password to launch the lastFrontAppPkg if the pass is correct
}
}
}
} catch (Exception e) {
//e.printStackTrace();
}
}
}
}, 0, 1000);
The android application is bulit in such a way that when data is being sent(on clicking the button) to the usb device ,LED toggles and the data is being displayed. I want data to be sent continuously without any manual intervention. Kindly help
if (mInputStream != null)
{
int Data = 0;
try {
Data = mInputStream.read();
} catch (IOException e) {
}
if (Data == LED_ON)
{
ledStatus.setText("LED is ON");
}
else if (Data == LED_OFF)
{
ledStatus.setText("LED is OFF");
}
else
{
ledStatus.setText("Request failed");
}
}
else
{
ledStatus.setText("mInputStream == null");
}
this time I have tested it myself...
it should definitely work
paste it in your onCreate() good luck :)
Timer t = new Timer();
t.schedule(new TimerTask(){
public void run(){
// write the method name here. which you want to call continuously
Log.d("timer", "timer");
}
},10, 1000);