Android Illustration Of Using Service As Well As Broadcastreceiver

Posted on

This instance present how to using Service to run long-time business inward background thread, together with also implement BroadcastReceiver to brand communication betwixt Activity together with Service.

Reference: Android Developers Guide – Services

If a ingredient starts the service past times calling startService() (which results inward a telephone telephone to onStartCommand()), together with thence the service remains running until it stops itself alongside stopSelf() or roughly other ingredient stops it past times calling stopService().

If a ingredient calls bindService() to create the service (and onStartCommand() is non called), together with thence the service runs exclusively every bit long every bit the ingredient is jump to it. Once the service is unbound from all clients, the arrangement destroys it.

The Android arrangement volition force-stop a service exclusively when retentivity is depression together with it must recover arrangement resources for the activity that has user focus. If the service is jump to an activity that has user focus, together with thence it’s less probable to last killed, together with if the service is declared to run inward the foreground (discussed later), together with thence it volition almost never last killed. Otherwise, if the service was started together with is long-running, together with thence the arrangement volition lower its seat inward the listing of background tasks over fourth dimension together with the service volition larn highly susceptible to killing—if your service is started, together with thence you lot must pattern it to gracefully grip restarts past times the system. If the arrangement kills your service, it restarts it every bit shortly every bit resources larn available in 1 trial to a greater extent than (though this also depends on the value you lot provide from onStartCommand(), every bit discussed later). For to a greater extent than data nearly when the arrangement powerfulness destroy a service, encounter the Processes together with Threading document.


<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android=""     xmlns:tools=""     android:layout_width="match_parent"     android:layout_height="match_parent"     android:padding="16dp"     android:orientation="vertical"     tools:context="com.blogspot.android_er.androidservice.MainActivity">      <TextView         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:layout_gravity="center_horizontal"         android:autoLink="web"         android:text=""         android:textStyle="bold" />      <Button         android:id="@+id/startservice"         android:layout_width="match_parent"         android:layout_height="wrap_content"         android:text="Start Service"/>     <Button         android:id="@+id/stopservice"         android:layout_width="match_parent"         android:layout_height="wrap_content"         android:text="Stop Service"/>     <EditText         android:id="@+id/msgtosend"         android:layout_width="match_parent"         android:layout_height="wrap_content"         android:hint="msg to send..." />     <Button         android:id="@+id/send"         android:layout_width="match_parent"         android:layout_height="wrap_content"         android:text="Send msg to service"/>     <TextView         android:id="@+id/cntreceived"         android:layout_width="match_parent"         android:layout_height="wrap_content"         android:textStyle="bold"         android:textSize="26dp"/>     <TextView         android:id="@+id/msgreceived"         android:layout_width="match_parent"         android:layout_height="match_parent"         android:textStyle="bold"         android:textSize="20dp"/>  </LinearLayout>

package com.blogspot.android_er.androidservice;  import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView;  world degree MainActivity extends AppCompatActivity {      Button btnStart, btnStop, btnSend;     EditText editTextMsgToSend;     TextView textViewCntReceived, textViewMsgReceived;      MyMainReceiver myMainReceiver;     Intent myIntent = null;      @Override     protected void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.activity_main);         btnStart = (Button)findViewById(;         btnStop = (Button)findViewById(;         btnSend = (Button)findViewById(;         editTextMsgToSend = (EditText)findViewById(;         textViewCntReceived = (TextView)findViewById(;         textViewMsgReceived = (TextView)findViewById(;          btnStart.setOnClickListener(new View.OnClickListener() {             @Override             world void onClick(View v) {                 startService();             }         });          btnStop.setOnClickListener(new View.OnClickListener() {             @Override             world void onClick(View v) {                 stopService();             }         });          btnSend.setOnClickListener(new View.OnClickListener() {             @Override             world void onClick(View v) {                 String msgToService = editTextMsgToSend.getText().toString();                  Intent intent = novel Intent();                 intent.setAction(MyService.ACTION_MSG_TO_SERVICE);                 intent.putExtra(MyService.KEY_MSG_TO_SERVICE, msgToService);                 sendBroadcast(intent);             }         });     }      somebody void startService(){         myIntent = novel Intent(MainActivity.this, MyService.class);         startService(myIntent);     }      somebody void stopService(){         if(myIntent != null){             stopService(myIntent);         }         myIntent = null;     }      @Override     protected void onStart() {         myMainReceiver = novel MyMainReceiver();         IntentFilter intentFilter = novel IntentFilter();         intentFilter.addAction(MyService.ACTION_UPDATE_CNT);         intentFilter.addAction(MyService.ACTION_UPDATE_MSG);         registerReceiver(myMainReceiver, intentFilter);         super.onStart();     }      @Override     protected void onStop() {         unregisterReceiver(myMainReceiver);         super.onStop();     }      @Override     protected void onDestroy() {         super.onDestroy();         stopService();     }      somebody degree MyMainReceiver extends BroadcastReceiver {          @Override         world void onReceive(Context context, Intent intent) {             String activity = intent.getAction();             if(action.equals(MyService.ACTION_UPDATE_CNT)){                 int int_from_service = intent.getIntExtra(MyService.KEY_INT_FROM_SERVICE, 0);                 textViewCntReceived.setText(String.valueOf(int_from_service));             }else if(action.equals(MyService.ACTION_UPDATE_MSG)){                 String string_from_service = intent.getStringExtra(MyService.KEY_STRING_FROM_SERVICE);                 textViewMsgReceived.setText(String.valueOf(string_from_service));             }         }     } }

package com.blogspot.android_er.androidservice;  import; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.IBinder; import; import android.widget.Toast;  world degree MyService extends Service {      //from MyService to MainActivity     concluding static String KEY_INT_FROM_SERVICE = "KEY_INT_FROM_SERVICE";     concluding static String KEY_STRING_FROM_SERVICE = "KEY_STRING_FROM_SERVICE";     concluding static String ACTION_UPDATE_CNT = "UPDATE_CNT";     concluding static String ACTION_UPDATE_MSG = "UPDATE_MSG";      //from MainActivity to MyService     concluding static String KEY_MSG_TO_SERVICE = "KEY_MSG_TO_SERVICE";     concluding static String ACTION_MSG_TO_SERVICE = "MSG_TO_SERVICE";      MyServiceReceiver myServiceReceiver;     MyServiceThread myServiceThread;     int cnt;      @Nullable     @Override     world IBinder onBind(Intent intent) {         provide null;     }      @Override     world void onCreate() {         Toast.makeText(getApplicationContext(),                 "onCreate", Toast.LENGTH_LONG).show();         myServiceReceiver = novel MyServiceReceiver();         super.onCreate();     }      @Override     world int onStartCommand(Intent intent, int flags, int startId) {         Toast.makeText(getApplicationContext(),                 "onStartCommand", Toast.LENGTH_LONG).show();          IntentFilter intentFilter = novel IntentFilter();         intentFilter.addAction(ACTION_MSG_TO_SERVICE);         registerReceiver(myServiceReceiver, intentFilter);          myServiceThread = novel MyServiceThread();         myServiceThread.start();          provide super.onStartCommand(intent, flags, startId);     }      @Override     world void onDestroy() {         Toast.makeText(getApplicationContext(),                 "onDestroy", Toast.LENGTH_LONG).show();         myServiceThread.setRunning(false);         unregisterReceiver(myServiceReceiver);         super.onDestroy();     }      world degree MyServiceReceiver extends BroadcastReceiver {          @Override         world void onReceive(Context context, Intent intent) {              String activity = intent.getAction();             if(action.equals(ACTION_MSG_TO_SERVICE)){                 String msg = intent.getStringExtra(KEY_MSG_TO_SERVICE);                  msg = novel StringBuilder(msg).reverse().toString();                  //send dorsum to MainActivity                 Intent i = novel Intent();                 i.setAction(ACTION_UPDATE_MSG);                 i.putExtra(KEY_STRING_FROM_SERVICE, msg);                 sendBroadcast(i);             }         }     }      somebody degree MyServiceThread extends Thread{          somebody boolean running;          world void setRunning(boolean running){             this.running = running;         }          @Override         world void run() {             cnt = 0;             running = true;             spell (running){                 endeavour {                     Thread.sleep(1000);                      Intent intent = novel Intent();                     intent.setAction(ACTION_UPDATE_CNT);                     intent.putExtra(KEY_INT_FROM_SERVICE, cnt);                     sendBroadcast(intent);                      cnt++;                 } grab (InterruptedException e) {                     e.printStackTrace();                 }             }         }     } }  

Modify AndroidManifest.xml to add together <service> of “.MyService”.

<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android=""     package="com.blogspot.android_er.androidservice">      <application         android:allowBackup="true"         android:icon="@mipmap/ic_launcher"         android:label="@string/app_name"         android:supportsRtl="true"         android:theme="@style/AppTheme">         <activity android:name=".MainActivity">             <intent-filter>                 <action android:name="android.intent.action.MAIN" />                  <category android:name="android.intent.category.LAUNCHER" />             </intent-filter>         </activity>         <service android:name=".MyService"/>     </application>  </manifest> 

 This instance present how to using Service to run long Android instance of using Service together with BroadcastReceiverDownload the files .

– Example of IntentService together with BroadcastReceiver

– Android instance of using Thread together with Handler