comingage
comingage

Reputation: 55

check internet connection in background service every 30 min

Hello I want to make an app that will check internet connection in background every 30mins and if so it will send some really small json data to server.

Don't know if doing right but now I have:

package com.example.lenovotp.sender;

import android.app.AlarmManager;
import android.app.IntentService;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.widget.Toast;

import java.util.Calendar;


public class MyClass extends IntentService{
    private static final String TAG = "com.example.lenovotp.sender";
    private AlarmManager alarmMgr;
    private PendingIntent alarmIntent;
    Calendar calendar = Calendar.getInstance();
    public MyClass(){
        super("");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        AlarmManager alarmMgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    intent = new Intent(this, MyClass.class);
    PendingIntent alarmIntent = PendingIntent.getService(this, 0, intent, 0);
    alarmMgr.set(AlarmManager.RTC_WAKEUP,
            1000 * 30, alarmIntent);

    ConnectivityManager cm =
            (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    boolean isConnected = activeNetwork != null &&
            activeNetwork.isConnectedOrConnecting();
    //boolean isWiFi = activeNetwork.getType() == ConnectivityManager.TYPE_WIFI;
    if(isConnected!=false){
        Toast.makeText(this, "Network is avail!", Toast.LENGTH_LONG).show();
    } else {
        Toast.makeText(this, "Network is NOT avail!", Toast.LENGTH_LONG).show();
    }

    }
}

And in manifest I have in last postition in is

<?xml version="1.0" encoding="utf-8"?>

<!-- Permissions -->
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.USE_CREDENTIALS" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>

<application
    android:allowBackup="true"
    android:icon="@mipmap/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>
   <service android:name=".MyClass"/>
</application>

And in MainActivity

package com.example.lenovotp.sender;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Intent intent = new Intent(this,MyClass.class);
        startService(intent);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

So now I don't know how to:

  1. make it work even app is not running or destroyed by user.
  2. it check connectivity every 30mins and if so it sends some data to server.

Thanks in advance.

UPDATED

Upvotes: 0

Views: 3266

Answers (1)

Karakuri
Karakuri

Reputation: 38605

A few things:

  1. Subclass IntentService instead of Service. Services run on the main (UI) thread, but an IntentService will do its work in a background thread (in onHandleIntent()), and it automatically stops itself after finishing its work.
  2. In your service, use AlarmManager to schedule your next "wakeup" in 30 minutes. You can find numerous examples how to use AlarmManager all over the web.
  3. You may need a way to schedule the first "wakeup" of your service after the device boots. For this you'll need a BroadcastReceiver in your manifest that is registered to receive the ACTION_BOOT_COMPLETED broadcast. This requires you to have the RECEIVE_BOOT_COMPLETED permission. Examples of this are all over the web as well.

Upvotes: 4

Related Questions