Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shake Device to Launch App

I am using this to work with Shake, and that works fine for me, but i wanna launch application when user shake their device, see my code below:

 @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    transcript=(TextView)findViewById(R.id.transcript);
    scroll=(ScrollView)findViewById(R.id.scroll);

    shaker=new Shaker(this, 1.25d, 500, this);
  }

  @Override
  public void onDestroy() {
    super.onDestroy();

    shaker.close();
  }

  public void shakingStarted() {
    Log.d("ShakerDemo", "Shaking started!");
    transcript.setText(transcript.getText().toString()+"Shaking started\n");
    scroll.fullScroll(View.FOCUS_DOWN);
  }

  public void shakingStopped() {
    Log.d("ShakerDemo", "Shaking stopped!");
    transcript.setText(transcript.getText().toString()+"Shaking stopped\n");
    scroll.fullScroll(View.FOCUS_DOWN);
  }

So here is my question, how can i launch an application by shaking my device ?

like image 387
Sun Avatar asked Mar 11 '14 08:03

Sun


1 Answers

You should write Android Service that will start your activity during shake. That is all. Services run in the background even if Activity is not visible

Service can be started eg. during device boot. This can be achieved using BroadCastReceiver.

Manifest:

<application ...>
    <activity android:name=".ActivityThatShouldBeLaunchedAfterShake" />
    <service android:name=".ShakeService" />
    <receiver android:name=".BootReceiver">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
    </receiver>
</application>

BootReceiver:

public class BootReceiver extends BroadcastReceiver {
    public void onReceive(Context context, Intent intent) {
        Intent intent = new Intent(context, ShakeService.class);
        context.startService(intent);
    }
}

Service:

public class ShakeService extends Service {
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    ... somewhere
    if(shaked) {
        Intent intent = new Intent(getApplicationContext(), ActivityThatShouldBeLaunchedAfterShake.class)
            .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }
}
like image 102
Gaskoin Avatar answered Sep 22 '22 01:09

Gaskoin