我一直在使用广播接收器开发一个没有 UI 的简单应用程序。
该应用不包含任何 Activity 。
我已授予必要的权限。
我从这个网址获取了代码:http://developerandro.blogspot.in/2013/09/check-internet-connection-using.html
当我点击更改 wifi 状态时,该应用程序显示“未连接到互联网”提示框。它工作正常。
但我的问题是我的 list 文件中注册了一个我没有的 Activity 。所以我从 list 中删除了这些行。然后没有显示 toast ,我也检查了日志。更改 wifi 状态时没有输出。
为什么会这样?请帮帮我...
这是 list 文件:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.broadcast_internetcheck"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.broadcast_internetcheck.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>
<receiver
android:name="com.example.broadcast_internetcheck.NetworkChangeReceiver"
android:label="NetworkChangeReceiver" >
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
<action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
</intent-filter>
</receiver>
</application>
</manifest>
这是我的 Broadcastreceiver 类:
public class NetworkChangeReceiver extends BroadcastReceiver{
@Override
public void onReceive(final Context context, final Intent intent) {
String status = NetworkUtil.getConnectivityStatusString(context);
/*Above line will return the status of wifi */
Toast.makeText(context, status, Toast.LENGTH_LONG).show();
}
}
最佳答案
您需要为服务创建一个虚拟 Activity ,该 Activity 将在虚拟 Activity 的 onCreate()
中触发,可能是具有 finish()
的非 UI .
没有它,所需的实现是不可能的,尤其是在 Android 3.1 以上。
http://developer.android.com/about/versions/android-3.1.html#launchcontrols
Run only a background service when application start
Start android application without activity
http://commonsware.com/blog/2011/07/13/boot-completed-regression-confirmed.html
关于服务的更多信息:
http://developer.android.com/guide/components/services.html
https://developer.android.com/training/run-background-service/create-service.html
http://www.vogella.com/tutorials/AndroidServices/article.html
关于没有 GUI 的 Android 应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21772458/