我需要在后台检查互联网连接.... 我在我的数据库中保存一些数据,每当我上网时, 它应该在我的服务器上传数据... 我需要一个后台服务,即使我关闭我的应用程序,也会连续检查互联网连接, 我尝试了一些方法,但只有在我打开我的应用程序时它们才有效... 目前我正在检查这样的互联网连接
/checking internet connection
ConnectivityManager connectivityManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
if(connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED ||
connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED) {
//we are connected to a network
connected = true;
}
else
//not connected to internet
connected = false;
if(connected) {
//getting teacher data if INTERNET_STATE is true(if will be still true if connected to a wifi or network without internet)
getOfflineSubjectData();
getTeacherData();
}
else{
getOfflineSubjectData();
Toast.makeText(teacher_homePage.this,"no internet",Toast.LENGTH_SHORT).show();
}
注意 我不想要一个在关闭我的应用程序后无效的方法... 就像我们关闭应用程序时的whatsapp一样,我们仍然会收到短信
答案 0 :(得分:5)
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.widget.Toast;
public class CheckConnectivity extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent arg1) {
boolean isConnected = arg1.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
if(isConnected){
Toast.makeText(context, "Internet Connection Lost", Toast.LENGTH_LONG).show();
}
else{
Toast.makeText(context, "Internet Connected", Toast.LENGTH_LONG).show();
}
}
}
Android清单
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.connect.broadcast"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="8" android:targetSdkVersion="8"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<receiver android:exported="false"
android:name=".CheckConnectivity" >
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
</application>
</manifest>
答案 1 :(得分:3)
我知道回答你的问题为时已晚,但仍然是一个完美的解决方案。
我们可以通过同时使用服务和广播接收器轻松实现,以获得您想要的输出。这将始终有效,即应用程序运行时,应用程序最小化或甚至从最小化的应用程序中删除应用程序。
清单代码:
<application
...
<service android:name=".MyService" />
</application>
MyService.java
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.widget.Toast;
public class MyService extends Service {
static final String CONNECTIVITY_CHANGE_ACTION = "android.net.conn.CONNECTIVITY_CHANGE";
NotificationManager manager ;
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// Let it continue running until it is stopped.
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
IntentFilter filter = new IntentFilter();
filter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (CONNECTIVITY_CHANGE_ACTION.equals(action)) {
//check internet connection
if (!ConnectionHelper.isConnectedOrConnecting(context)) {
if (context != null) {
boolean show = false;
if (ConnectionHelper.lastNoConnectionTs == -1) {//first time
show = true;
ConnectionHelper.lastNoConnectionTs = System.currentTimeMillis();
} else {
if (System.currentTimeMillis() - ConnectionHelper.lastNoConnectionTs > 1000) {
show = true;
ConnectionHelper.lastNoConnectionTs = System.currentTimeMillis();
}
}
if (show && ConnectionHelper.isOnline) {
ConnectionHelper.isOnline = false;
Log.i("NETWORK123","Connection lost");
//manager.cancelAll();
}
}
} else {
Log.i("NETWORK123","Connected");
showNotifications("APP" , "It is working");
// Perform your actions here
ConnectionHelper.isOnline = true;
}
}
}
};
registerReceiver(receiver,filter);
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
}
}
ConnectionHelper.java
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
public class ConnectionHelper {
public static long lastNoConnectionTs = -1;
public static boolean isOnline = true;
public static boolean isConnected(Context context) {
ConnectivityManager cm =(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
return activeNetwork != null && activeNetwork.isConnected();
}
public static boolean isConnectedOrConnecting(Context context) {
ConnectivityManager cm =(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
return activeNetwork != null &&
activeNetwork.isConnectedOrConnecting();
}
}
您的活动代码
startService(new Intent(getBaseContext(), MyService.class));
答案 2 :(得分:0)
可能有一些更好的方法,但我已经将此实现为@Rahul建议的STICK_SERVICE,并且为了避免杀死服务,我在状态栏中强制执行固定通知。我知道这可能不是一个好习惯,但是客户要求显示&#34;应用程序正在运行...&#34;在状态栏中,所以没关系。
<强> SyncService.class 强>
public class SyncService extends IntentService {
private static int FOREGROUND_ID = 1338;
public Boolean isServiceRunning = false;
Integer delay;
private NotificationManager mgr;
public SyncService() {
super("SyncService");
}
@Override
public void onStart(@Nullable Intent intent, int startId) {
super.onStart(intent, startId);
}
@Override
public void onCreate() {
super.onCreate();
}
@Override
public void onDestroy() {
super.onDestroy();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
performSync();
startSyncThread();
mgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
final NotificationCompat.Builder builder = buildForeground();
startForeground(1, builder.build());
return START_STICKY;
}
public Boolean isWifiConnected() {
ConnectivityManager connManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
return mWifi.isConnected();
}
public void startSyncThread() {
Handler handler = new Handler();
delay = 1000;
handler.postDelayed(new Runnable() {
public void run() {
performSync();
handler.postDelayed(this, delay);
}
}, delay);
}
public void performSync() {
if (isWifiConnected()) {
Log.i("SyncService:", "Wifi connected, start syncing...");
Sync sync = new Sync(this);
sync.postPhotos();
sync.postEvents();
sync.getEvents();
delay = 60000;
} else {
Log.i("SyncService:", "Wifi IS NOT connected, ABORT syncing...");
delay = 1000;
}
Log.i("SyncService:", delay + "");
}
@Override
protected void onHandleIntent(Intent intent) {
WakefulReceiver.completeWakefulIntent(intent);
}
private NotificationCompat.Builder buildForeground() {
Intent intent = new Intent(this, EventsActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
NotificationCompat.Builder b = new NotificationCompat.Builder(this);
b.setContentTitle("Prime Share is running")
.setSmallIcon(android.R.drawable.stat_notify_sync_noanim)
.setOngoing(true)
.setAutoCancel(false)
.setPriority(Notification.PRIORITY_MAX)
.setContentIntent(pendingIntent);
return (b);
}
}
然后在我的第一个关于创造的活动中,我称之为:
context = this;
startSyncIntent = new Intent(this, SyncService.class);
startService(startSyncIntent);
答案 3 :(得分:-1)
map <- get_googlemap(center = 'middle east', zoom = 4,
style = 'feature:administrative.country|element:labels|visibility:off')
plot <- ggmap(map)
print(plot)
在任何地方使用此方法
public static boolean isNetworkAvailable(Context context) {
ConnectivityManager connectivity = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity == null) {
return false;
} else {
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null) {
for (int i = 0; i < info.length; i++) {
if (info[i].getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
}
}
return false;
}
答案 4 :(得分:-1)
如果您需要在后台检查互联网,即使应用被杀,也必须实施sticky service。这将坚持在后台,并将为您上传工作。创建一个数据库或任何其他持久性存储,您可以在其中保存数据并保持其状态。
对于例如 - 如果上传数据,则将其状态标记为true
或将其从数据库中删除,并在下次获取状态不是true
或尚未发送到服务器的数据时。
答案 5 :(得分:-1)
创建BroadcastReceiver以收听互联网连接
public class InternetConnectivityReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
boolean isConnected = networkInfo != null && networkInfo.isConnectedOrConnecting();
if (networkChangedListener != null) {
networkChangedListener.onNetworkConnectionChanged(isConnected);
}
}
public static boolean isInternetConnected() {
ConnectivityManager connectivityManager = (ConnectivityManager) CustomApplication.getInstance()
.getApplicationContext()
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
return networkInfo != null && networkInfo.isConnectedOrConnecting();
}
}
然后在Android Manifest中配置接收器
<application
.............>
<receiver android:name=".BroadcastReceiver.InternetConnectivityReceiver" />
.............
</application>
然后检查您的活动中的互联网连接
if (!InternetConnectivityReceiver.isInternetConnected()) {
Toast.makeText(teacher_homePage.this,"No Internet Connection",Toast.LENGTH_SHORT).show();
} else if (InternetConnectivityReceiver.isInternetConnected()) {
Toast.makeText(context, "Internet Connected", Toast.LENGTH_LONG).show();
}
答案 6 :(得分:-1)
使用计时器代码检查互联网访问,我已经为此做了一项服务 我第一次在堆栈上发布....所以提前抱歉,因为我无法以良好的格式发布它
private Handler mHandler = new Handler();
private Timer mTimer = null;
long notify_interval = 1000;
public static String str_receiver = "pravin.service.receiver";
Intent intent;
DatabaseHandler dh=new DatabaseHandler(this);
public CheckInternet(){
}
@Override
public void onCreate()
{
mTimer = new Timer();
mTimer.schedule(new TimerTaskToGetInternetStatus(), 5, notify_interval);
intent = new Intent(str_receiver);
}
private class TimerTaskToGetInternetStatus extends TimerTask {
@Override
public void run() {
mHandler.post(new Runnable() {
@Override
public void run() {
icConnected();
}
});
}
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onStart(Intent intent,int startid)
{
}
public boolean icConnected()
{
Log.d("Called " , "INTERNET");
ConnectivityManager connec =
(ConnectivityManager)getSystemService(getBaseContext().CONNECTIVITY_SERVICE);
// Check for network connections
if ( connec.getNetworkInfo(0).getState() == android.net.NetworkInfo.State.CONNECTED ||
connec.getNetworkInfo(0).getState() == android.net.NetworkInfo.State.CONNECTING ||
connec.getNetworkInfo(1).getState() == android.net.NetworkInfo.State.CONNECTING ||
connec.getNetworkInfo(1).getState() == android.net.NetworkInfo.State.CONNECTED ) {
Log.d("INTERNET","TRUE");
dh.getIssues();
return true;
// if connected with internet
//makeText(this, " Connected ", LENGTH_LONG).show();
} else if (
connec.getNetworkInfo(0).getState() == android.net.NetworkInfo.State.DISCONNECTED ||
connec.getNetworkInfo(1).getState() == android.net.NetworkInfo.State.DISCONNECTED ) {
Log.d("INTERNET","FALSE");
return false;
//makeText(this, " Not Connected ", LENGTH_LONG).show();
}
return false;
}
}