What is the best way to keep an android application's thread (other than the UI thread) running even after the application is closed?
-
I mean, I need to find a way to allow user to start a task(a time-consuming & repetitive one) and then continue the task even after the onDestroy() method is called for the application. And later when the user starts the application next time, I wish to give the user an option to stop that background task. Any suggestions/guidance would be really appreciated. Thanks!
-
Answer:
You can do this with the help of a Service in Android. Look at this link for a tutorial http://saigeethamn.blogspot.in/2009/09/android-developer-tutorial-for_22.html Activities are killed by Android when its in need of memory. Services are rarely killed. You can start an ongoing Service http://developer.android.com/reference/android/app/Service.html#startForeground%28int,%20android.app.Notification%29 . Here the service runs in the foreground and probablity of it dying is very low.
Suhas Grama at Quora Visit the source
Other answers
Make it a Service. .. which is like a daemon process in Unix.
Nalin Savara
I think "services" is your answer. In android, if you want anything to run in background even after closing the activity, you should do it as a ser
Ambalika Saha
Make it a service and it will run in background.... you may refer to foll. tutorial : http://www.vogella.com/articles/AndroidServices/article.html
Ayushi Gupta
You can use BroadcastReceiver to achive your requriment . check following code. activity_alarm_manager.xml <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <Button android:id="@+id/btStart" android:layout_width="match_parent" android:layout_height="wrap_content" android:padding="@dimen/padding_medium" android:text="@string/btStart" android:onClick="startRepeatingTimer" tools:context=".WidgetAlarmManagerActivity" /> <Button android:id="@+id/btCancel" android:layout_width="match_parent" android:layout_height="wrap_content" android:padding="@dimen/padding_medium" android:text="@string/btCancel" android:onClick="cancelRepeatingTimer" /> <Button android:id="@+id/btOneTime" android:layout_width="match_parent" android:layout_height="wrap_content" android:padding="@dimen/padding_medium" android:text="@string/btOneTime" android:onClick="onetimeTimer" /> </LinearLayout> AlarmManagerActivity.java public class AlarmManagerActivity extends Activity { private AlarmManagerBroadcastReceiver alarm; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_alarm_manager); alarm = new AlarmManagerBroadcastReceiver(); } @Override protected void onStart() { super.onStart(); } public void startRepeatingTimer(View view) { Context context = this.getApplicationContext(); if(alarm != null){ alarm.SetAlarm(context); }else{ Toast.makeText(context, "Alarm is null", Toast.LENGTH_SHORT).show(); } } public void cancelRepeatingTimer(View view){ Context context = this.getApplicationContext(); if(alarm != null){ alarm.CancelAlarm(context); }else{ Toast.makeText(context, "Alarm is null", Toast.LENGTH_SHORT).show(); } } public void onetimeTimer(View view){ Context context = this.getApplicationContext(); if(alarm != null){ alarm.setOnetimeTimer(context); }else{ Toast.makeText(context, "Alarm is null", Toast.LENGTH_SHORT).show(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_widget_alarm_manager, menu); return true; } } AlarmManagerBroadcastReceiver.java public class AlarmManagerBroadcastReceiver extends BroadcastReceiver { final public static String ONE_TIME = "onetime"; @Override public void onReceive(Context context, Intent intent) { PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE); PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "YOUR TAG"); //Acquire the lock wl.acquire(); //You can do the processing here update the widget/remote views. Bundle extras = intent.getExtras(); StringBuilder msgStr = new StringBuilder(); if(extras != null && extras.getBoolean(ONE_TIME, Boolean.FALSE)){ msgStr.append("One time Timer : "); } Format formatter = new SimpleDateFormat("hh:mm:ss a"); msgStr.append(formatter.format(new Date())); Toast.makeText(context, msgStr, Toast.LENGTH_LONG).show(); //Release the lock wl.release(); } public void SetAlarm(Context context) { AlarmManager am=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE); Intent intent = new Intent(context, AlarmManagerBroadcastReceiver.class); intent.putExtra(ONE_TIME, Boolean.FALSE); PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, 0); //After after 30 seconds am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 1000 * 5 , pi); } public void CancelAlarm(Context context) { Intent intent = new Intent(context, AlarmManagerBroadcastReceiver.class); PendingIntent sender = PendingIntent.getBroadcast(context, 0, intent, 0); AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); alarmManager.cancel(sender); } public void setOnetimeTimer(Context context){ AlarmManager am=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE); Intent intent = new Intent(context, AlarmManagerBroadcastReceiver.class); intent.putExtra(ONE_TIME, Boolean.TRUE); PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, 0); am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), pi); } } Manifest.xml <uses-sdk android:minSdkVersion="10" android:targetSdkVersion="15" /> <!-- Permissions --> <uses-permission android:name="android.permission.WAKE_LOCK"/> <application android:icon="@drawable/ic_launcher" android:label="@string/app_name" > <activity android:name=".AlarmManagerActivity" android:label="@string/title_activity_alarm_manager" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <!-- Broadcast receiver --> <receiver android:name=".AlarmManagerBroadcastReceiver"></receiver> </application>
Vishwa Dani
Use Android's services! U can't have the UI thread run in the background for ever since android closes apps when they run out of memory!! Using services u can run apps which doesn't have to have a UI! See android documentation for more details
Anjith Sasindran
Related Q & A:
- What is the best way to distribute an audio/video feed from a computer to TVs over existing indoor coax cable?Best solution by Audio-Video Production
- What is the best way to clean LEGO bricks?Best solution by bricks.stackexchange.com
- What is the best way to make UI for an Isometric game in Java?Best solution by Game Development
- What is the best way to calculate a date difference?Best solution by Stack Overflow
- What is the best way to count lines in file?Best solution by Stack Overflow
Just Added Q & A:
- How many active mobile subscribers are there in China?Best solution by Quora
- How to find the right vacation?Best solution by bookit.com
- How To Make Your Own Primer?Best solution by thekrazycouponlady.com
- How do you get the domain & range?Best solution by ChaCha
- How do you open pop up blockers?Best solution by Yahoo! Answers
For every problem there is a solution! Proved by Solucija.
-
Got an issue and looking for advice?
-
Ask Solucija to search every corner of the Web for help.
-
Get workable solutions and helpful tips in a moment.
Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.