我整天都在遇到一個大問題。我有一個應用程序,它在設備啓動時運行正常,唯一的問題是該應用程序需要啓動互聯網連接,並且在應用程序啓動之前wifi沒有連接。所以我使用BroadcastReceiver和WifiManager的組合來確定是否有WiFi連接。我唯一的問題,如果它通過了有連接的測試,那麼我想在MainActivity.java
中運行onCreate。連接互聯網/無線網絡時運行代碼
我該怎麼做?我對Java非常陌生,並且對整個事情感到困惑,但很快就有所收穫。
我有這樣的代碼在我MainActivity.java
:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView myWebView = (WebView) findViewById(R.id.webview);
myWebView.setWebViewClient(new WebViewClient());
myWebView.getSettings().setJavaScriptEnabled(true);
myWebView.loadUrl("http://www.example.com");
}
這裏是內部SMSReceiver.Java代碼:
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.wifi.WifiManager;
public class SMSReceiver extends BroadcastReceiver
{
@Override
public void onReceive(Context context, Intent intent) {
WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
wifiManager.setWifiEnabled(true);
if(wifiManager.isWifiEnabled()){
//Call onCreate in MainActivity.java
}
}
}
這裏是清單代碼:
<application
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>
<activity
android:name=".SMSReceiver"
android:label="@string/title_activity_smsreceiver" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
我究竟做錯了什麼?
UPDATE
我更改SMSReceiver到接收器,而不是像這樣的活動:
<receiver android:name=".SMSReceiver ">
<intent-filter>
<action android:name="android.intent.action.YOUR_FILTER_OR_SOME_STANDARD" />
</intent-filter>
</receiver>
現在我該怎麼辦?
你AndroidManifest應該聲明SMSReceiver作爲接收器,而不是一個活動。然後添加意圖操作和權限以監聽BOOT_COMPLETED意圖。 – 2014-09-19 19:58:40