Skip to content

Instantly share code, notes, and snippets.

@groupsky
Created June 17, 2015 18:32
Show Gist options
  • Save groupsky/2af8f1b866ff5ed99a65 to your computer and use it in GitHub Desktop.
Save groupsky/2af8f1b866ff5ed99a65 to your computer and use it in GitHub Desktop.
Android Services & Alarms
<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"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity">
<Button
android:id="@+id/start_service"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Start service" />
<Button
android:id="@+id/stop_service"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Stop service" />
<Button
android:id="@+id/long_calc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Long calculation"/>
<Button
android:id="@+id/bind"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Bind"/>
<Button
android:id="@+id/unbind"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Unbind"/>
<Button
android:id="@+id/binded_op"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Binded operation"/>
<Button
android:id="@+id/set_alarm"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Set alarm"/>
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="org.hackafe.servicesalarms" >
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".MyService"
android:enabled="true"
android:exported="true" >
</service>
<service
android:name=".MyIntentService"
android:exported="false" >
</service>
</application>
</manifest>
package org.hackafe.servicesalarms;
import android.app.Activity;
import android.app.AlarmManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
public class MainActivity extends Activity implements View.OnClickListener, ServiceConnection {
public static final String TAG = MyIntentService.TAG;
private IBinder service;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.start_service).setOnClickListener(this);
findViewById(R.id.stop_service).setOnClickListener(this);
findViewById(R.id.long_calc).setOnClickListener(this);
findViewById(R.id.bind).setOnClickListener(this);
findViewById(R.id.unbind).setOnClickListener(this);
findViewById(R.id.binded_op).setOnClickListener(this);
findViewById(R.id.set_alarm).setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.start_service:
Log.d(MyService.TAG, "startService = " +
startService(new Intent(this, MyIntentService.class)));
break;
case R.id.stop_service:
Log.d(MyService.TAG, "stopService = " +
stopService(new Intent(this, MyIntentService.class)));
break;
case R.id.long_calc:
MyIntentService.startActionFoo(this, null, null);
break;
case R.id.bind:
Log.d(TAG, "bindService = "+
bindService(
new Intent(this, MyIntentService.class), this, BIND_AUTO_CREATE));
break;
case R.id.unbind:
unbindService(this);
break;
case R.id.binded_op:
MyIntentService.LocalBinder lb = (MyIntentService.LocalBinder) service;
Log.d(TAG, "concat = "+lb.concat("abc", "def"));
Log.d(TAG, "sum = "+lb.getService().sum(10, 25));
break;
case R.id.set_alarm:
setAlarm();
break;
}
}
private void setAlarm() {
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
}
@Override
protected void onResume() {
super.onResume();
LocalBroadcastManager.getInstance(this).registerReceiver(receiver, new IntentFilter(MyIntentService.ACTION_FOO_RESULT));
}
@Override
protected void onPause() {
LocalBroadcastManager.getInstance(this).unregisterReceiver(receiver);
super.onPause();
}
private BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG, "received broadcast " + intent);
MyIntentService.startActionBaz(context, "param1", "param2");
}
};
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
Log.d(TAG, "onServiceConnected " + name + " service = " + service);
this.service = service;
}
@Override
public void onServiceDisconnected(ComponentName name) {
Log.d(TAG, "onServiceDisconnected "+name);
this.service = null;
}
}
package org.hackafe.servicesalarms;
import android.app.IntentService;
import android.content.Intent;
import android.content.Context;
import android.content.res.Configuration;
import android.os.Binder;
import android.os.IBinder;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import java.awt.font.TextAttribute;
/**
* An {@link IntentService} subclass for handling asynchronous task requests in
* a service on a separate handler thread.
* <p/>
* TODO: Customize class - update intent actions, extra parameters and static
* helper methods.
*/
public class MyIntentService extends IntentService {
public static final String TAG = MyService.TAG;
// TODO: Rename actions, choose action names that describe tasks that this
// IntentService can perform, e.g. ACTION_FETCH_NEW_ITEMS
public static final String ACTION_FOO = "org.hackafe.servicesalarms.action.FOO";
public static final String ACTION_BAZ = "org.hackafe.servicesalarms.action.BAZ";
// TODO: Rename parameters
public static final String EXTRA_PARAM1 = "org.hackafe.servicesalarms.extra.PARAM1";
public static final String EXTRA_PARAM2 = "org.hackafe.servicesalarms.extra.PARAM2";
public static final String ACTION_FOO_RESULT = "foo result";
/**
* Starts this service to perform action Foo with the given parameters. If
* the service is already performing a task this action will be queued.
*
* @see IntentService
*/
// TODO: Customize helper method
public static void startActionFoo(Context context, String param1, String param2) {
Intent intent = new Intent(context, MyIntentService.class);
intent.setAction(ACTION_FOO);
intent.putExtra(EXTRA_PARAM1, param1);
intent.putExtra(EXTRA_PARAM2, param2);
context.startService(intent);
}
/**
* Starts this service to perform action Baz with the given parameters. If
* the service is already performing a task this action will be queued.
*
* @see IntentService
*/
// TODO: Customize helper method
public static void startActionBaz(Context context, String param1, String param2) {
Intent intent = new Intent(context, MyIntentService.class);
intent.setAction(ACTION_BAZ);
intent.putExtra(EXTRA_PARAM1, param1);
intent.putExtra(EXTRA_PARAM2, param2);
context.startService(intent);
}
public MyIntentService() {
super("MyIntentService");
Log.d(TAG, "created!!!!");
}
@Override
protected void onHandleIntent(Intent intent) {
try {
Log.d(TAG, "onHandleIntent " + intent);
if (intent != null) {
final String action = intent.getAction();
if (ACTION_FOO.equals(action)) {
final String param1 = intent.getStringExtra(EXTRA_PARAM1);
final String param2 = intent.getStringExtra(EXTRA_PARAM2);
handleActionFoo(param1, param2);
} else if (ACTION_BAZ.equals(action)) {
final String param1 = intent.getStringExtra(EXTRA_PARAM1);
final String param2 = intent.getStringExtra(EXTRA_PARAM2);
handleActionBaz(param1, param2);
}
}
} catch (Throwable t) {
Log.w(TAG, "crash detected!", t);
}
}
/**
* Handle action Foo in the provided background thread with the provided
* parameters.
*/
private void handleActionFoo(String param1, String param2) {
try {
Log.d(TAG, "long oper start");
Thread.sleep(1000 * 10);
LocalBroadcastManager localBroadcastManager = LocalBroadcastManager.getInstance(this);
localBroadcastManager.sendBroadcast(
new Intent(ACTION_FOO_RESULT)
.putExtra(EXTRA_PARAM1, "1000")
);
Log.d(TAG, "long oper end");
} catch (InterruptedException e) {
Log.w(TAG, "interrupted", e);
}
}
/**
* Handle action Baz in the provided background thread with the provided
* parameters.
*/
private void handleActionBaz(String param1, String param2) {
// TODO: Handle action Baz
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public void onCreate() {
Log.d(TAG, "onCreate!!!!");
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(TAG, "onStartCommand, intent = " + intent + " flags = " + Integer.toHexString(flags) + " startId = " + startId);
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
Log.d(TAG, "onDestroy");
super.onDestroy();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
Log.d(TAG, "onConfigurationChanged = " + newConfig);
super.onConfigurationChanged(newConfig);
}
@Override
public void onLowMemory() {
Log.d(TAG, "onLowMemory");
super.onLowMemory();
}
@Override
public void onTrimMemory(int level) {
Log.d(TAG, "onTrimMemory");
super.onTrimMemory(level);
}
@Override
public boolean onUnbind(Intent intent) {
Log.d(TAG, "onUnbind, intent = " + intent);
return super.onUnbind(intent);
}
@Override
public void onRebind(Intent intent) {
Log.d(TAG, "onRebind, intent = "+intent);
super.onRebind(intent);
}
@Override
public void onTaskRemoved(Intent rootIntent) {
Log.d(TAG, "onTaskRemoved, rootIntent = "+rootIntent);
super.onTaskRemoved(rootIntent);
}
@Override
public IBinder onBind(Intent intent) {
Log.d(TAG, "onBind "+intent);
return mBinder;
}
private final IBinder mBinder = new LocalBinder();
/**
* Class used for the client Binder. Because we know this service always
* runs in the same process as its clients, we don't need to deal with IPC.
*/
public class LocalBinder extends Binder {
public MyIntentService getService() {
// Return this instance of LocalService so clients can call public methods
return MyIntentService.this;
}
public String concat(String a, String b) {
Log.d(TAG, "concat "+a+", "+b);
return a+b;
}
}
public int sum(int a, int b) {
Log.d(TAG, "sum "+a+", "+b);
return a+b;
}
}
package org.hackafe.servicesalarms;
import android.app.Service;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.IBinder;
import android.util.Log;
public class MyService extends Service {
public static final String TAG = "-+= MYSERVICE =+-";
public MyService() {
Log.d(TAG, "created!!!!");
}
@Override
public void onCreate() {
Log.d(TAG, "onCreate!!!!");
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(TAG, "onStartCommand, intent = "+intent+" flags = "+Integer.toHexString(flags)+" startId = "+startId);
if (intent != null) {
switch (intent.getStringExtra("TYPE")) {
case "LONG":
try {
Thread.sleep(1000*60*5);
} catch (InterruptedException e) {
Log.w(TAG, "interrupted", e);
}
break;
}
}
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
Log.d(TAG, "onDestroy");
super.onDestroy();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
Log.d(TAG, "onConfigurationChanged = "+newConfig);
super.onConfigurationChanged(newConfig);
}
@Override
public void onLowMemory() {
Log.d(TAG, "onLowMemory");
super.onLowMemory();
}
@Override
public void onTrimMemory(int level) {
Log.d(TAG, "onTrimMemory");
super.onTrimMemory(level);
}
@Override
public boolean onUnbind(Intent intent) {
Log.d(TAG, "onUnbind, intent = "+intent);
return super.onUnbind(intent);
}
@Override
public void onRebind(Intent intent) {
Log.d(TAG, "onRebind, intent = "+intent);
super.onRebind(intent);
}
@Override
public void onTaskRemoved(Intent rootIntent) {
Log.d(TAG, "onTaskRemoved, rootIntent = "+rootIntent);
super.onTaskRemoved(rootIntent);
}
@Override
public IBinder onBind(Intent intent) {
Log.d(TAG, "onBind");
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment