java - 摇动设备启动应用程序

标签 java android shake

我正在使用 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);
  }

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

最佳答案

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

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

list :

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

关于java - 摇动设备启动应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22319601/

相关文章:

java - 如果文件已重命名,如何跟踪?

java - 如何通过 id 更改 fxml 标签文本

android - 为 Kotlin 多平台项目运行单元测试时出错

安卓FTP下载

iphone - 如何在 Cocos2d CCLayer 中添加摇动手势?

ios - iPad 不检测摇动事件

java - 使用 Android 异步 HTTP 时没有得到响应(来自 loopj)

java - SonarQube 没有在 javadoc 中显示错误

java - 使用向上按钮导航回相应的 fragment

jquery - jquery摇动效果后(显示:none) why?