我使用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);
}下面是我的问题,,我如何通过摇晃我的设备来启动应用程序?
发布于 2014-03-21 20:22:29
您应该编写Android服务,以便在抖动期间启动您的活动。这就是全部。即使活动不可见,服务也在后台运行。
服务可以开始。在设备启动的时候。这可以使用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);
}
}发布于 2014-03-15 09:05:01
为Shake detection编写一个单独的应用程序。在检测到抖动时,使用app的包名启动一个意图,您想要启动:
Intent intent = new Intent (<PackageNameOfAppToBeLaunched>);
startActivity (intent);发布于 2014-03-20 18:12:33
那么,您需要的是两个不同的活动,其中第一个检测到您的摇动,需要一直运行在后台,而不是调用新的实际应用程序,你想要运行的摇。
您可以运行您的后台活动,您必须使用类,这将使您的活动在后台运行很长时间(连续),您可以使用类,如FutureTask或Executor (您不能使用AsyncTask )。
每当线程在Shake之后将命令传递给您的应用程序,后台进程就会停止,并且命令转到app,这意味着您需要在实际的应用程序关闭后再次立即启动后台进程。
https://stackoverflow.com/questions/22319601
复制相似问题