如何获得调用BroadcastReceiver的活动?

时间:2017-04-07 04:48:14

标签: android broadcastreceiver android-fragmentactivity

我有 //Create ROle Class public ActionResult CreateRole(FormCollection collection) { try { var context = new ApplicationDbContext(); // RoleStore // var newRole = new AspNetRoles(); // ontext.Roles.Add(new ApplicationRole) { // not visible... context.Roles.Add(new Microsoft.AspNet.Identity.EntityFramework.IdentityRole() { Name = collection["RoleName"], }); context.SaveChanges(); ViewBag.Message = "Role created successfully !"; ... //Extended Role Class public class ApplicationRole : IdentityRole { public ApplicationRole() : base() { } public ApplicationRole(string name) : base(name) { } public string Description { get; set; } public string CompanyId { get; set; } } 检查NetworkChange,无论是否连接到Internet。

因此,在我的应用程序中,当网络断开连接或连接时,我想知道哪个活动调用了BroadcastReceiver,以便在显示通知网络的警报后我可以返回上一个活动。

我的代码,

BroadcastReceiver

在上面的代码中,当重新连接Internet时,  public class NetworkChangeReceiver extends BroadcastReceiver { private android.widget.Toast Toast; @Override public void onReceive(final Context context, final Intent intent) { try { boolean isVisible = MyApplication.isActivityVisible(); Context appContext = context.getApplicationContext(); if (isVisible == true) { if (checkInternet(context)) { /*Intent i = new Intent(context, MainActivity.class); i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(i);*/ Toast.makeText(context, "Network Available Do operations", Toast.LENGTH_LONG).show(); } else { Intent i = new Intent(context, NoNetworkAlert.class); i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(i); Toast.makeText(context, "Network NOT Available Do operations", Toast.LENGTH_LONG).show(); } ......... ...... 我只是想参加触发此活动的活动。

3 个答案:

答案 0 :(得分:1)

我假设顶部的当前活动是触发NetworkChangeListener的活动。如果是这样,您可以使用下面的代码段,

ActivityManager am = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);
ComponentName cn = am.getRunningTasks(1).get(0).topActivity;

会将当前活动放在最顶层。

答案 1 :(得分:0)

在您的活动中执行类似的操作

BroadcastReceiver br=new NetworkChangeReceiver ();
        IntentFilter filter = new IntentFilter();
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        this.registerReceiver(br, filter);

在你的宣言中

<receiver
            android:name=".NetworkChangeReceiver "
            android:exported="true">
            <intent-filter>

                <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
                <action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
            </intent-filter>
        </receiver>

答案 2 :(得分:0)

我有一个BroadcastReceiver,用于检查NetworkChange,无论是否连接到Internet。 因此,在我的应用程序中,当网络断开连接或连接时,我想知道哪个活动调用了BroadcastReceiver,这样我就可以在显示通知网络的警报后返回上一个活动。

要获取广播接收器中的当前活动,请使用广播接收器中的ActivityManager来获取不带实例的活动

ActivityManager am = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);
ComponentName cn = am.getRunningTasks(1).get(0).topActivity;
Log.i("ActivityManager ", "ActivityManager" + cn.toString());

要使用实例更好地使用实例获取活动,请使用Getter和Setter。

MyApplication.Java:

public class MyApplication extends Application {
   private Activity mCurrentActivity = null;
   // Gloabl declaration of variable to use in whole app
   public static boolean activityVisible; // Variable that will check the
                                 // current activity state
   public static boolean isActivityVisible() {
      return activityVisible; // return true or false
   }
   public static void activityResumed() {
      activityVisible = true;// this will set true when activity resumed
   }
   public static void activityPaused() {
      activityVisible = false;// this will set false when activity paused
   }
   public Activity getCurrentActivity(){
      return mCurrentActivity;
   }
   public void setCurrentActivity(Activity mCurrentActivity){
      this.mCurrentActivity = mCurrentActivity;
   }
}

MainActivity.Java:

public class MainActivity extends AppCompatActivity {
    private static TextView internetStatus;
    protected MyApplication mMyApp;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mMyApp = (MyApplication) this.getApplicationContext();
        internetStatus = (TextView) findViewById(R.id.internet_status);
        // At activity startup we manually check the internet status and change
        // the text status
        ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        if (networkInfo != null && networkInfo.isConnected()) {
            changeTextStatus(true);
        } else {
            changeTextStatus(false);
        }
    }
    // Method to change the text status
    public void changeTextStatus(boolean isConnected) {
        // Change status according to boolean value
        if (isConnected) {
            internetStatus.setText("Internet Connected.");
            internetStatus.setTextColor(Color.parseColor("#00ff00"));
        } else {
            internetStatus.setText("Internet Disconnected.");
            internetStatus.setTextColor(Color.parseColor("#ff0000"));
        }
    }
    @Override
    protected void onPause() {
        super.onPause();
        MyApplication.activityPaused();// On Pause notify the Application
        clearReferences();
    }
    @Override
    protected void onResume() {
        super.onResume();
        MyApplication.activityResumed();// On Resume notify the Application
        mMyApp.setCurrentActivity(this);
    }
    protected void onDestroy() {
        clearReferences();
        super.onDestroy();
    }
    private void clearReferences() {
        Activity currActivity = mMyApp.getCurrentActivity();
        Log.e("Activity", "Activity" + currActivity);
        if (this.equals(currActivity))
            mMyApp.setCurrentActivity(null);
    }
}

InternetConnector_Receiver.Java:

public class InternetConnector_Receiver extends BroadcastReceiver {
    public InternetConnector_Receiver() {
    }
    @Override
    public void onReceive(Context context, Intent intent) {
        try {
            boolean isVisible = MyApplication.isActivityVisible();
            Log.i("Activity is Visible ", "Is activity visible : " + isVisible);
            ActivityManager am = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);
            ComponentName cn = am.getRunningTasks(1).get(0).topActivity;
           Log.i("ActivityManager", "Activity Name:" + cn.toString());
            // If it is visible then trigger the task else do nothing
            if (isVisible == true) {
                ConnectivityManager connectivityManager = (ConnectivityManager) context
                        .getSystemService(Context.CONNECTIVITY_SERVICE);
                NetworkInfo networkInfo = connectivityManager
                        .getActiveNetworkInfo();
                // Check internet connection and accrding to state change the
                // text of activity by calling method
                if (networkInfo != null && networkInfo.isConnected()) {
                    new MainActivity().changeTextStatus(true);
                } else {
                    new MainActivity().changeTextStatus(false);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

清单许可:

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />


<application
    android:name="com.internetconnection_demo.MyApplication"
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name=".MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <!-- Broadcast receiver declaration in manifest file and make sure to enable it -->
    <receiver
        android:name="com.internetconnection_demo.InternetConnector_Receiver"
        android:enabled="true" >
        <intent-filter>
            <!-- Intent filters for broadcast receiver -->
            <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
            <action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
            <action android:name="android.net.wifi.STATE_CHANGE" />
        </intent-filter>
    </receiver>
</application>