【问题标题】:Shake Device to Launch App摇动设备以启动应用程序
【发布时间】:2014-03-11 08:01:22
【问题描述】:

我正在使用 this 与 Shake 一起工作,这对我来说很好,但我想在用户摇动他们的设备时启动应用程序, 请参阅下面的代码:

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

所以这是我的问题,如何通过摇晃我的设备来启动应用程序?

【问题讨论】:

  • 我有问题。现在启动您的应用时晃动您的设备,您的应用显示屏会捕捉到它吗?

标签: java android shake


【解决方案1】:

您应该编写将在摇动期间启动您的活动的 Android 服务。就这些。即使 Activity 不可见,服务也会在后台运行

可以启动服务,例如。在设备启动期间。这可以使用 BroadCastReceiver 来实现。

清单:

<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>

引导接收器:

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

服务:

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

【讨论】:

    【解决方案2】:

    Shake detection 编写一个单独的应用程序。在检测到抖动时,使用您要启动的应用程序包名称触发意图:

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

    【讨论】:

    • 是的,把它放在前台:)
    【解决方案3】:

    你需要的是两个不同的活动,第一个是检测你的 Shake,它需要一直在后台运行,然后调用你想要在摇动时运行的新的实际应用程序。

    你可以运行你的后台活动,你必须使用类,这将使你的活动在后台运行很长时间(连续)你可以使用像FutureTaskExecutor这样的类(你不能 为此使用AsyncTask)。

    只要线程将命令传递给您的应用程序在摇动后台进程停止并且命令转到应用程序后打开,这意味着您需要在实际应用程序关闭后立即再次启动后台进程。

    【讨论】:

      【解决方案4】:

      您需要编写代码,以便在摇动开始时将应用程序从后台启动到前台。这个link 将帮助您做到这一点。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-10-28
        • 1970-01-01
        • 2014-04-18
        • 2021-04-25
        • 2020-02-10
        相关资源
        最近更新 更多