2014-05-08 17 views
0

我的清單中有一個接收器。接收器在Android清單中的兩個動作

<receiver 
    android:name="com.deviceinventory.StartAppAtBootReceiver" 
    android:enabled="true" 
    android:exported="false" 
    android:label="StartMyServiceAtBootReceiver" > 
    <intent-filter> 
      <action android:name="android.intent.action.BOOT_COMPLETED" /> 
    </intent-filter> 
</receiver> 

而且我com.deviceinventory.StartAppAtBootReceiver的onReceive()是

public void onReceive(Context context, Intent intent) {  
    if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) { 
     Intent startUpIntent = new Intent(context, StartUpActivity.class); 
     startUpIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
     context.startActivity(startUpIntent); 
    } 

由於StartUpActivity使用互聯網,所以我想,當互聯網連接可用開機後啓動該活動。

目前它在互聯網連接建立之前的某個時間開始。

我不知道如何修改清單中的接收器和BroadCastReceiver

+1

你需要聽'ConnectivityManager.CONNECTIVITY_ACTION'行動廣播... –

+0

然後開始活動之前,你應該檢查網絡的可用性。 –

+0

@SimplePlan我必須在連接可用後開始活動, –

回答

1

爲此,您需要添加一個Receiver來檢查Internet連接是否啓用/禁用,當它啓用時,您可以啓動您的bootReceiver或您想運行的任何活動。

public class NetworkInfoReceiver extends BroadcastReceiver { 

@Override 
public void onReceive(final Context context, final Intent intent) { 
try { 
    /*** 
    * Here we need to check its running perfectly means this receiver 
    * call when net is off/on. You should have to check 
    * */ 
    final ConnectivityManager conMngr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); 

    // Check if we are connected to an active data network. 
    final NetworkInfo activeNetwork = conMngr.getActiveNetworkInfo(); 
    final boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting(); 

    if (isConnected) { 
    /** 
    * Start service/receiver/activity here. 
    * */ 

    } else { 
    /** 
    * Stop service/receiver/activity here. 
    * */ 
    } 
} catch (final Exception e) { 
} 
} 
} 

然後您將此接收器添加到AndroidManifest.xml文件中。

 <receiver 
     android:name=".NetworkInfoReceiver" 
     android:enabled="true" > 
     <intent-filter> 
      <action android:name="android.net.conn.CONNECTIVITY_CHANGE" /> 
     </intent-filter> 
    </receiver> 
0

您可以嘗試編輯您的意圖過濾器。現在,您的recierver會在完全引導設備時作出響應。當連接改變時,改變它以響應它...

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

希望這段代碼能幫助你。

+0

這將在連接發生變化時啓動活動。我只想在連接啓動後才啓動 –

0

@您需要檢查onReceive是否符合條件才能啓動服務。


public void onReceive(Context context, Intent intent) { 
ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE); 
WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); 
     if(intent.equals(Intent.ACTION_BOOT_COMPLETE) && wifiManager.isWifiEnabled()){ 
     //start your service 
     } 
} 
+0

@Hemant這會幫助你 – Atta

相關問題