本文介绍了摇动设备,以启动应用程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的this与摇工作,这为我工作正常,但我想启动应用程序时,用户摇动他们的设备,见下面我的code:

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

因此​​,这里是我的问题,我如何可以启动通过摇动我的设备的应用程序?

推荐答案

您应该编写Android的服务,这将动摇中开始你的活动。这是所有。服务在后台运行,即使活动是不可见的。

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

服务,才能启动,例如。在设备启动。这可以使用的BroadcastReceiver可以实现。

Service can be started eg. during device boot. This can be achieved using 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>

BootReceiver:

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

这篇关于摇动设备,以启动应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 02:16