Shake Device to Launch App

后端 未结 4 1986
孤独总比滥情好
孤独总比滥情好 2021-01-02 20:52

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
           


        
4条回答
  •  爱一瞬间的悲伤
    2021-01-02 21:02

    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

    Service can be started eg. during device boot. This can be achieved using BroadCastReceiver.

    Manifest:

    
        
        
        
                
                    
                
        
    
    

    BootReceiver:

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

    Service:

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

提交回复
热议问题