Shake Device to Launch App

不问归期 提交于 2019-11-30 14:18:22

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);
    }
}

Write a separate app for Shake detection. On detection of shake, fire an intent with the package name of app, you want to launch:

Intent intent = new Intent (<PackageNameOfAppToBeLaunched>);     
startActivity (intent);

Well What you need is Two different activity Where first One Detects your Shake which need to run all time in background and than call the new actual app you want to run on shake.

You can run your background activity you have to use class which will keep your activity run in background for long time(Continuously) you can use classes Like FutureTask or Executor (you can not use AsyncTask for this).

Whenever the thread passes command to Your Application open after Shake the Background process stops and command goes to app means you need to again immediately start background process after the actual app closed.

Nithin Michael

You need to write the code to launch the application to foreground from background while the shake started. This link will help you to do so.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!