简体   繁体   中英

Call a method of an Activity from a class

I have Activity named BarcodeScanActivity which has a method OnScanDataPass . I want to access this method from a non Activity class (Normal Calss).

public class BarcodeScanActivity : Activity, EMDKManager.IEMDKListener
{
     static IScanDataPass _scanDataPass;

     public void OnScanDataPass(IScanDataPass scanDataPass)
     {
         _scanDataPass = scanDataPass;
     }
}

below is my class

public class ScanCode_Android : IScanCode, IScanDataPass
{
        static Context context = Application.Context;
        private Intent intent = new Intent(context,typeof(BarcodeScanActivity));
        private BarcodeScanActivity scan = new BarcodeScanActivity();

        public ScanCode_Android()
        {
            context.StartActivity(intent);
            scan.OnScanDataPass(this);
        }
}

Above code snippet shows the method i tried. How do I call a method in an activity from a normal class? How can I do it with Intent?

You can not instantiate an Activity manually, the instance of Activity will be instantiated by System, and its process is complex.


You can pass the instance of Activity to your Normal Class to achieve your goal:

public class ScanCode_Android : IScanCode, IScanDataPass 
{ 
        BarcodeScanActivity mContext ;

        public ScanCode_Android(BarcodeScanActivity context) 
        {   
            this.mContext=context;
            Intent intent = new Intent(context,typeof(BarcodeScanActivity));
            context.StartActivity(intent);
            context.OnScanDataPass(this);
        } 
}

How can I do it with Intent?

You need use Context to deal with it. Like StartActivity, StartService... .

How do I call a method in an activity from a normal class?

Like the above codes, pass Activity to Normal class.

Update:

You can create one pixel Activity to avoid the Activity to been seen.

OnePiexlActivity :

[Activity(Label = "OnePiexlActivity",Theme = "@style/OnePixelActivity")]
public class OnePiexlActivity : Activity
{
    protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);
        Window.SetGravity(GravityFlags.Left | GravityFlags.Top);
        WindowManagerLayoutParams layoutParams=  Window.Attributes;
        layoutParams.X = 0;
        layoutParams.Y = 0;
        layoutParams.Height = 1;
        layoutParams.Width = 1;
        Window.Attributes=layoutParams;
        Android.Util.Log.Error("lv","111111111111");

    }
}

style :

<style name="OnePixelActivity" parent="android:Theme.Holo.Light.NoActionBar">
  <item name="android:windowIsTranslucent">true</item>
</style>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM