2017-04-07 10 views
0

私はBroadcastReceiverを持っていて、インターネットに接続されているかどうかにかかわらず、NetworkChangeをチェックしています。BroadcastReceiverを呼び出したアクティビティを取得するにはどうすればよいですか?

私のアプリケーションでは、ネットワークが切断または接続されているときに、どのアクティビティがBroadcastReceiverと呼ばれているかを知りたいので、ネットワークに関するアラートを表示して前のアクティビティに戻ることができます。

私のコード、インターネットが再接続された上記のコードではここ

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

    ......... 
    ...... 

、 私はちょうどこれを誘発される活性を取得したい if (checkInternet(context))

+0

「これを引き起こした」とは、意図を送ったエンティティを意味しますか?私はあなたができるとは思わない。これを行うシステムでなければなりません。 –

答えて

1

トップの現在のアクティビティがNetworkChangeListenerをトリガーするアクティビティだとします。その場合は、下記のコードスニペットを使用できます。

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

これは、現在のアクティビティを一番上に表示します。

0

は、あなたの活動に

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

をこのような何かをして、あなたのmenifest

<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> 
0

に私がインターネットに接続されているかいないかどうか、NetworkChangeをチェックBroadcastReceiverを持っています。 私のアプリケーションでは、ネットワークが切断または接続されているときに、どのアクティビティがBroadcastReceiverを呼び出したのかを知りたいので、ネットワークに関するアラートを表示して前のアクティビティに戻ることができます。

良好ゲッターとセッターを使用してインスタンスと兼ね備え活性のアクティビティを取得する

インスタンスなしアクティビティを取得する放送受信装置で
ActivityManager am = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE); 
ComponentName cn = am.getRunningTasks(1).get(0).topActivity; 
Log.i("ActivityManager ", "ActivityManager" + cn.toString()); 

をActivityManagerを使用する放送受信機における現在のアクティビティを取得します。

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> 
関連する問題