Created
February 2, 2017 09:46
-
-
Save talhahasanzia/a026d1732a61a60c56c891488951fbf1 to your computer and use it in GitHub Desktop.
Intent Service Example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class MainActivity extends AppCompatActivity | |
{ | |
private ResponseReceiver receiver; | |
@Override | |
protected void onCreate( Bundle savedInstanceState ) | |
{ | |
super.onCreate( savedInstanceState ); | |
setContentView( R.layout.activity_main ); | |
Intent msgIntent = new Intent(this, MyCustomService.class); | |
msgIntent.putExtra(MyCustomService.PARAM_IN_MSG, "Hello from main activity"); | |
startService(msgIntent); | |
IntentFilter filter = new IntentFilter(ResponseReceiver.ACTION_RESP); | |
filter.addCategory(Intent.CATEGORY_DEFAULT); | |
receiver = new ResponseReceiver(); | |
registerReceiver(receiver, filter); | |
} | |
public class ResponseReceiver extends BroadcastReceiver | |
{ | |
public static final String ACTION_RESP = | |
"MESSAGE_PROCESSED"; | |
@Override | |
public void onReceive(Context context, Intent intent) { | |
String text = intent.getStringExtra(MyCustomService.PARAM_OUT_MSG); | |
Log.d( "TAG", "onReceive: "+text ); | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class MyCustomService extends IntentService | |
{ | |
public static final String PARAM_IN_MSG = "imsg"; | |
public static final String PARAM_OUT_MSG = "omsg"; | |
public MyCustomService( ) | |
{ | |
super( "MyCustomService" ); | |
} | |
public MyCustomService( String name ) | |
{ | |
super( "MyCustomService" ); | |
} | |
@Override protected void onHandleIntent( Intent intent ) | |
{ | |
String msg = intent.getStringExtra( PARAM_IN_MSG ); | |
SystemClock.sleep( 10000 ); // 30 seconds | |
String resultTxt = msg + " " | |
+ DateFormat.format( "MM/dd/yy h:mmaa", System.currentTimeMillis() ); | |
Log.d( msg, resultTxt ); | |
Intent broadcastIntent = new Intent(); | |
broadcastIntent.setAction( MainActivity.ResponseReceiver.ACTION_RESP ); | |
broadcastIntent.addCategory( Intent.CATEGORY_DEFAULT ); | |
broadcastIntent.putExtra( PARAM_OUT_MSG, resultTxt ); | |
sendBroadcast( broadcastIntent ); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Refer to this link for bound services in Android.