Example Of Intentservice In Addition To Broadcastreceiver

Posted on

Last post service exhibit instance of using Service in addition to BroadcastReceiver, this instance exhibit how to practise the same chore using IntentService and BroadcastReceiver.


layout/activity_main.xml

<?xml version="1.0" encoding="utf-8"?> <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: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="https://rootandroid.org//"         android:textStyle="bold" />      <Button         android:id="@+id/startservice"         android:layout_width="match_parent"         android:layout_height="wrap_content"         android:text="Start 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>  

MainActivity.java

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 android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView;  populace bird MainActivity extends AppCompatActivity {      Button btnStart, 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(R.id.startservice);         btnSend = (Button)findViewById(R.id.send);         editTextMsgToSend = (EditText)findViewById(R.id.msgtosend);         textViewCntReceived = (TextView)findViewById(R.id.cntreceived);         textViewMsgReceived = (TextView)findViewById(R.id.msgreceived);          btnStart.setOnClickListener(new View.OnClickListener() {             @Override             populace void onClick(View v) {                 startService();             }         });          btnSend.setOnClickListener(new View.OnClickListener() {             @Override             populace void onClick(View v) {                 String msgToService = editTextMsgToSend.getText().toString();                  Intent intent = novel Intent();                 intent.setAction(MyIntentService.ACTION_MSG_TO_SERVICE);                 intent.putExtra(MyIntentService.KEY_MSG_TO_SERVICE, msgToService);                 sendBroadcast(intent);             }         });     }      somebody void startService(){         myIntent = novel Intent(MainActivity.this, MyIntentService.class);         startService(myIntent);     }      @Override     protected void onStart() {         myMainReceiver = novel MyMainReceiver();         IntentFilter intentFilter = novel IntentFilter();         intentFilter.addAction(MyIntentService.ACTION_UPDATE_CNT);         intentFilter.addAction(MyIntentService.ACTION_UPDATE_MSG);         registerReceiver(myMainReceiver, intentFilter);         super.onStart();     }      @Override     protected void onStop() {         unregisterReceiver(myMainReceiver);         super.onStop();     }      @Override     protected void onDestroy() {         super.onDestroy();     }      somebody bird MyMainReceiver extends BroadcastReceiver {          @Override         populace void onReceive(Context context, Intent intent) {             String activity = intent.getAction();             if(action.equals(MyIntentService.ACTION_UPDATE_CNT)){                 int int_from_service = intent.getIntExtra(MyIntentService.KEY_INT_FROM_SERVICE, 0);                 textViewCntReceived.setText(String.valueOf(int_from_service));             }else if(action.equals(MyIntentService.ACTION_UPDATE_MSG)){                 String string_from_service = intent.getStringExtra(MyIntentService.KEY_STRING_FROM_SERVICE);                 textViewMsgReceived.setText(String.valueOf(string_from_service));             }         }     } }  

MyIntentService.java

package com.blogspot.android_er.androidservice;  import android.app.IntentService; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Looper; import android.widget.Toast;  populace bird MyIntentService extends IntentService {      //from MyIntentService to MainActivity     terminal static String KEY_INT_FROM_SERVICE = "KEY_INT_FROM_SERVICE";     terminal static String KEY_STRING_FROM_SERVICE = "KEY_STRING_FROM_SERVICE";     terminal static String ACTION_UPDATE_CNT = "UPDATE_CNT";     terminal static String ACTION_UPDATE_MSG = "UPDATE_MSG";      //from MainActivity to MyIntentService     terminal static String KEY_MSG_TO_SERVICE = "KEY_MSG_TO_SERVICE";     terminal static String ACTION_MSG_TO_SERVICE = "MSG_TO_SERVICE";      MyServiceReceiver myServiceReceiver;     int cnt;      populace MyIntentService() {         super("MyIntentService");     }      @Override     populace void onCreate() {         Toast.makeText(getApplicationContext(),                 "onCreate", Toast.LENGTH_LONG).show();         myServiceReceiver = novel MyServiceReceiver();         super.onCreate();     }      @Override     populace 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);          provide super.onStartCommand(intent, flags, startId);     }      @Override     populace void onDestroy() {         Toast.makeText(getApplicationContext(),                 "onDestroy", Toast.LENGTH_LONG).show();         unregisterReceiver(myServiceReceiver);         super.onDestroy();     }      @Override     protected void onHandleIntent(Intent intent) {          String prompt;         //check if electrical flow thread is Main Thread (UI)         if(Looper.myLooper() == Looper.getMainLooper()){             prompt = "onHandleIntent run inward UI Thread";         }else{             prompt = "onHandleIntent run inward NOT UI Thread";         }          Intent iPrompt = novel Intent();         iPrompt.setAction(ACTION_UPDATE_MSG);         iPrompt.putExtra(KEY_STRING_FROM_SERVICE, prompt);         sendBroadcast(iPrompt);          cnt = 10;         spell (cnt >= 0){             endeavour {                 Thread.sleep(1000);                  Intent i = novel Intent();                 i.setAction(ACTION_UPDATE_CNT);                 i.putExtra(KEY_INT_FROM_SERVICE, cnt);                 sendBroadcast(i);                  cnt--;             } grab (InterruptedException e) {                 e.printStackTrace();             }         }     }      populace bird MyServiceReceiver extends BroadcastReceiver {          @Override         populace 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);             }         }     }  }  

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

<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/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=".MyIntentService"/>     </application>  </manifest> 

 this instance exhibit how to practise the same chore using Example of IntentService in addition to BroadcastReceiverDownload the files .

Related:
– Android instance of using Thread in addition to Handler