我正在使用 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/