androidandroid-intentbroadcastreceiverandroid-task

Hide / Unhide application when connect / disconnect USB BroadcastReceiver


My application only have MainActivity with a ImageView.

BroadcastReceiver works. The Toast Message is displayed When I connect USB.

Now, I need start my application minimized and show the application only the USB cable was connected.

BroadcastReceiver broadcast_reciever = new BroadcastReceiver() {

    @Override
    public void onReceive(Context arg0, Intent intent) {
        String action = intent.getAction();
        if (action.equals("usb_detect")) {
            Toast.makeText(arg0,"Atenção!",Toast.LENGTH_SHORT).show();
            finish();
            startActivity(getIntent());
            //startActivity(new Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_LAUNCHER));
        }
    }
};

Manifest is here: https://i.sstatic.net/sa3Pe.jpg


Solution

  • To bring your application to the foreground, add the following to onReceive():

    Intent launchIntent = getPackageManager().
        getLaunchIntentForPackage("your.package.name");
    startActivity(launchIntent);
    

    This will not start a new Activity, it will simply bring the existing task containing your application to the foreground in whatever state it was in when it got moved to the background.

    Also, remove the call to finish() from your BroadcastReceiver. finish() is only used on an Activity.