Learn Python


Click to Learn Python3

Monday, November 21, 2011

Running a service in background on Android


Here the code is generate to run some process in background through service. For example we are running the time in background and displaying it in the UI. The service coding will be in a seperate class MyService.java


MyService.java
package com.services.demo;

import java.util.Date;
import android.app.Service; import android.content.Intent; import android.os.Handler; import android.os.IBinder; public class MyService extends Service { public static final String BROADCAST_ACTION = "com.services.demo.ServiceDemoActivity"; private final Handler handler = new Handler(); Intent intent;

int counter = 0; @Override public void onCreate() { // Called on service created intent = new Intent(BROADCAST_ACTION); } @Override

public void onDestroy() { // Called on service stopped }

@Override public void onStart(Intent intent, int startid) { int i = 0; while (i < 101) { if (i > 100) { this.onDestroy(); } else { counter = i; i++; handler.removeCallbacks(sendUpdatesToUI); handler.postDelayed(sendUpdatesToUI, 1 * 1000); // 1 sec }

} } private Runnable sendUpdatesToUI = new Runnable() { public void run() { DisplayLoggingInfo(); handler.postDelayed(this, 1 * 1000); // 1 sec }

}; private void DisplayLoggingInfo() { intent.putExtra("time", new Date().toLocaleString()); intent.putExtra("counter", String.valueOf(counter)); sendBroadcast(intent); }

public static boolean isRunning() { return true; } @Override

public IBinder onBind(Intent intent) { return null; } }

So for starting the service and stopping the service we will be using


Java
startService(new Intent(ServiceDemoActivity.this, MyService.class));
stopService(new Intent(ServiceDemoActivity.this, MyService.class));

For updating the UI we need to use the broadcast service. In that BroadcastReceiver we will update the UI

Java
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
updateDate(intent);
}

}; private void updateDate(Intent intent) { String time = intent.getStringExtra("time"); TextView date = (TextView) findViewById(R.id.date); date.setText(time); }
In the MyService.java the method DisplayLoggingInfo() will send the broadcast to the activity to update the UI, the UI xml code is
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:orientation="vertical"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent"
 >
<TextView
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 android:text="@string/hello"
 android:id="@+id/notification"
 />

 <TextView
 android:layout_width="fill_parent" android:id="@+id/date"
 android:layout_height="wrap_content" android:text="" android:gravity="center" android:textSize="20sp" android:padding="20dp"/>
 <Button android:id="@+id/stop" android:text="Stop Service" android:layout_width="wrap_content" android:layout_height="wrap_content" />
</LinearLayout>

If we are opening the application on the first time means, it will be like this

and if we go out and come back to the page means, it will be showing a message like this

and if we stop the service means, it will be showing a message like this



You can download the full source code



Download source


Have a good day.

18 comments:

  1. Please, renew link to the source

    ReplyDelete
  2. Thank you for detailed information on Android codes. Get Android Training from onlineitguru experts

    ReplyDelete
  3. Freelancer In India
    The students belonging to different places, unable to attend regular classes get access to educational courses across a wide range of programs. It provides facilities for students to communicate with faculty regarding Free Sourcecode For Academic. If you want to read more :- Free Source Code|Free Sourcecode For Academic|Academic Project Download|Academic Project Free Download|Freelancer In India. E-mail :- info@nikhilbhalerao.com ph. no. +91 9423979339 https://nikhilbhalerao.com/. #Free_Source_Code #Free_Sourcecode_For_Academic

    ReplyDelete
  4. This comment has been removed by the author.

    ReplyDelete
  5. This comment has been removed by the author.

    ReplyDelete
  6. This comment has been removed by the author.

    ReplyDelete
  7. Thank you so much for sharing your brilliant thoughts with us. Visit Ogen Infosystem for professional Web Designing and SEO Services in Delhi, India.
    Website Designing Company in Delhi

    ReplyDelete
  8. X-Byte Enterprise Solution is a leading blockchain, AI, & IoT Solution company in USA and UAE, We have expert Web & mobile app development services

    Know more here: https://www.xbytesolutions.com/

    ReplyDelete
  9. Have you ever thought about publishing an e-book or guest authoring on other sites? I have a blog based upon on the same subjects you discuss and would love to have you share some stories/information. I know my subscribers would appreciate your work. If you're even remotely interested, feel free to shoot me an e-mail.
    vba programmierung berlin

    ReplyDelete
  10. Thank you for sharing this informative post.
    Keep sharing.
    Android App Development Course

    ReplyDelete
  11. BandiCam 6.0.4 Crack is a powerful video-recording software. It is built to capture videos from the computer system. Bandicam Key Generator

    ReplyDelete
  12. IDM crack is an acronym that stands for Internet Download Manager and this tool comes handy to handle all your download issues. IDM Full Version With Crack

    ReplyDelete
  13. EPR Authorization for E-waste

    EPR stands for Extended Producers Responsibility, which confers the responsibilities to Producers, importers, manufacturers, and brand owners to collect the e-waste and recycle it.

    Overview on EPR Authorization for E-waste
    EPR stands for Extended Producers Responsibility, is a policy of the government under which producers are given the vital responsibility for the treatment and disposal of the consumer goods. The EPR authorization is mandated for the producers, importers, manufacturers, and brand owners. EPR is a practice that encompasses a combination of environmental, economic, and social factors. EPR is a policy strategy in which producers are held financially and physically responsible for the handling and disposal of post-consumer items. Assigning such responsibility might, in theory, create incentives to reduce waste at the source, promote environmentally friendly product design, and support public recycling and waste management aims. The OECD is moving toward expanding EPR to include additional products, product groups, and waste streams such as electrical appliances and electronics products.
    EPR Registration for E-Waste
    Policies concerned with Extended Producer Responsibility
    In India, EPR came into existence to deal with E-waste. Therefore, the central government decided to introduce the E-waste management act 2016. The EPR focuses on:-

    ReplyDelete