0
The `MainActivity` registers with GCM Server and the  `IntentService` sends `RegId` to the server. Wi-Fi Push Notification is working well but when running on 3G network, the MainActivity screen looks like blank screen and goes in wait state. I have spent a lot of hours for that but does not get any solution.

I've  the updated code below work fine on 3G but Server Doesnot get RegId Shared using Application:

 package com.appiphy.virtualnoticeboard;

import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Handler;
import android.provider.Settings;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.WakefulBroadcastReceiver;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.widget.ImageView;
import android.widget.Toast;

import com.appiphy.virtualnoticeboard.notification.Config;
import com.appiphy.virtualnoticeboard.notification.ShareExternalServer;
import com.google.android.gms.gcm.GoogleCloudMessaging;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    private static int SPLASH_TIME_OUT = 1000;
    ImageView splahImage;
    String[] imageName;
    private Context _context;
    SharedPreferences megacare;
    String status;
    DatabaseHelper db;
    Handler myHandler;
    Runnable myRunnable;
    String  Msg, From;

    String regId,From_Whom;
    ArrayList<String> mylist = new ArrayList<String>();
    List<Notice> noticeList = new ArrayList<Notice>();    // server to db to noticeList
    public NotificationReceiver nReceiver;
    ShareExternalServer appUtil;
    public static final String REG_ID = "regId";
    private static final String APP_VERSION = "appVersion";
    GoogleCloudMessaging gcm;
    static final String TAG = "Register Activity";
    AsyncTask<Void, Void, String> shareRegidTask;
    String result;
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final SharedPreferences prefs1 = getSharedPreferences(
                MainActivity.class.getSimpleName(), Context.MODE_PRIVATE);
        regId = prefs1.getString(REG_ID, "");
        appUtil = new ShareExternalServer();
        Fragment gridView = new NoticeRowFragment();
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.replace(R.id.container_body, gridView);
        fragmentTransaction.commit();

      /*  if(isNetworkAvailable())*/ {

        new AsyncTask<Void, Void, String>() {
            @Override
            protected String doInBackground(Void... params) {
                if (regId.isEmpty())
                {
                    regId = registerGCM();
                }
                System.out.println("RegisterActivityregisterGCM - successfully registered with GCM server - regId: " + regId);
                return  regId;

            }
            @Override
            protected void onPostExecute(String msg) {
                Toast.makeText(getApplicationContext(),
                        "Registered with GCM Server." + msg, Toast.LENGTH_LONG)
                        .show();
            }
        }.execute(null, null, null);

            shareRegidTask = new AsyncTask<Void, Void, String>() {
                @Override
                protected String doInBackground(Void... params) {



                    if (!regId.isEmpty())
                    {
                            appUtil.shareRegIdWithAppServer(getApplicationContext(), regId);
                    }
                    else
                            result = appUtil.shareRegIdWithAppServer(getApplicationContext(), regId);


                    return result;

                }
                @Override
                protected void onPostExecute(String result)
                {
                    shareRegidTask = null;
                    Toast.makeText(getApplicationContext(), result,
                            Toast.LENGTH_LONG).show();
                }

            };
            shareRegidTask.execute(null, null, null);

            nReceiver = new NotificationReceiver();
            IntentFilter filter = new IntentFilter();
            filter.addAction("com.appiphy.spacecomp.spinnerframework1.Notification");
            registerReceiver(nReceiver, filter);

           /* Boolean value = isNotificationServiceRunning();
            if (!value) {
                startActivity(new Intent(Settings.ACTION_NOTIFICATION_LISTENER_SETTINGS));
            }
            try {
                regId = getIntent().getStringExtra("regId");
                Msg = getIntent().getStringExtra("Msg");
                From = getIntent().getStringExtra("From");
                //System.out.println("Message----InMain Activity.."+Msg);

                if (From.equalsIgnoreCase("Notification")) {
                    Fragment gridView1 = new NoticeRowFragment();
                    FragmentManager fragmentManager1 = getSupportFragmentManager();
                    FragmentTransaction fragmentTransaction1 = fragmentManager1.beginTransaction();
                    fragmentTransaction1.replace(R.id.container_body, gridView1);
                    fragmentTransaction1.commit();
                }

            } catch (Exception e) {
                e.printStackTrace();
            }*/
        }
       /* else
        {
            System.out.println("Check Network Connection");
        }*/
    }
    private boolean isNotificationServiceRunning()
    {
        ContentResolver contentResolver = getContentResolver();
        String enabledNotificationListeners = Settings.Secure.getString(contentResolver, "enabled_notification_listeners");
        String packageName = getPackageName();
        return enabledNotificationListeners != null && enabledNotificationListeners.contains(packageName);
    }

    @Override
    protected void onDestroy()
    {
        unregisterReceiver(nReceiver);
        super.onDestroy();
    }

    class NotificationReceiver extends WakefulBroadcastReceiver
    {

        @Override
        public void onReceive(Context context, Intent intent) {

            ComponentName comp = new ComponentName(context.getPackageName(),
                    MainActivity.class.getName());
            startWakefulService(context, (intent.setComponent(comp)));


            final SharedPreferences prefs1 = getSharedPreferences(
                    MainActivity.class.getSimpleName(), Context.MODE_PRIVATE);
            String flagNotify = prefs1.getString("broadcast", "");

            try {
                if (flagNotify.equalsIgnoreCase("broadcast1")) {
                    System.out.println("BraodCastReceiver Main Activity....................." + flagNotify);

                    //  mToolbar.setNavigationIcon(R.drawable.navigation_drawerwithdot);
                    //  mToolbar.setDrawerIndicatorEnabled(false);
                    // mToolbar.setHomeAsUpIndicator(R.drawable.navigation_drawerwithdot);
                    //mToolbar.setNavigationIcon(R.drawable.red_dot);
                    //toolBarImg.setImageResource(R.drawable.red_dot);
                    //toolBarImg.setVisibility(View.VISIBLE);
                } else if (flagNotify.equalsIgnoreCase("FromNotice")) {
                    System.out.println("BraodCastReceiver From Notice...MainActivity" + flagNotify);
                    //     toolBarImg.setVisibility(View.VISIBLE);
                    //  mToolbar.setNavigationIcon(R.drawable.navigation_drawer);

                    //   MainActivity.this.getSupportActionBar().setDisplayHomeAsUpEnabled(true);


                    //   mToolbar.setLogo(R.drawable.plus_black);
                    //   mToolbar.invalidate();
                 /*   ActionBar actionbar = getSupportActionBar();
                    actionbar.setDisplayHomeAsUpEnabled(true); // Enable
                    actionbar.setHomeAsUpIndicator(R.drawable.plus);*/
                    //    toolBarImg.setImageResource(R.drawable.plus);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public String registerGCM()
    {

        gcm = GoogleCloudMessaging.getInstance(this);
        regId = getRegistrationId(this);

        if (TextUtils.isEmpty(regId)) {

            registerInBackground();

            // Log.d("RegisterActivity", "registerGCM - successfully registered with GCM server - regId: "+ regId);
        } else {
            Toast.makeText(getApplicationContext(),
                    "RegId already available. RegId: " + regId,
                    Toast.LENGTH_LONG).show();
        }
        return regId;
    }

    private String getRegistrationId(Context context) {
        final SharedPreferences prefs = getSharedPreferences(
                MainActivity.class.getSimpleName(), Context.MODE_PRIVATE);
        regId  = prefs.getString(REG_ID, "");

       /* for (Iterator<String> it = registrationId.iterator(); it.hasNext();) {
            regId = it.next();
            System.out.println("foo found"+regId);
        }*/
        if (regId.isEmpty()) {
            //Log.i(TAG, "Registration not found.");
            return "";
        }
        int registeredVersion = prefs.getInt(APP_VERSION, Integer.MIN_VALUE);
        int currentVersion = getAppVersion(context);
        if (registeredVersion != currentVersion) {
            // Log.i(TAG, "App version changed.");
            return "";
        }
        return regId;
    }

    private static int getAppVersion(Context context)
    {
        try
        {
            PackageInfo packageInfo = context.getPackageManager()
                    .getPackageInfo(context.getPackageName(), 0);
            return packageInfo.versionCode;
        }
        catch (PackageManager.NameNotFoundException e)
        {
            // Log.d("RegisterActivity", "I never expected this! Going down, going down!" + e);
            throw new RuntimeException(e);
        }
    }

    private void registerInBackground() {
        new AsyncTask<Void, Void, String>() {
            @Override
            protected String doInBackground(Void... params) {
                String msg = "";
                try {
                    if (gcm == null) {
                        gcm = GoogleCloudMessaging.getInstance(getApplicationContext());
                    }
                    regId = gcm.register(Config.GOOGLE_PROJECT_ID);

                    // mylist.add(regId); //this adds an element to the list.
                    //Set<String> regIdSet = new HashSet<String>(mylist);
                    //Log.d("RegisterActivity", "registerInBackground - regId: " + regId);
                    msg = "Device registered, registration ID=" + regId;
                    System.out.println("Registration Id......InService"+regId);
                    storeRegistrationId(getApplicationContext(), regId);
                }
                catch (IOException ex)
                {
                    msg = "Error :" + ex.getMessage();
                    // Log.d("RegisterActivity", "Error: " + msg);
                }
                // Log.d("RegisterActivity", "AsyncTask completed: " + msg);
                return msg;
            }

            @Override
            protected void onPostExecute(String msg) {
                Toast.makeText(getApplicationContext(),
                        "Registered with GCM Server." + msg, Toast.LENGTH_LONG)
                        .show();
            }
        }.execute(null, null, null);
    }

    private void storeRegistrationId(Context context, String regId) {
        final SharedPreferences prefs = getSharedPreferences(
                MainActivity.class.getSimpleName(), Context.MODE_PRIVATE);
        int appVersion = getAppVersion(context);
        // Log.i(TAG, "Saving regId on app version " + appVersion);

        SharedPreferences.Editor editor = prefs.edit();
        editor.putString(REG_ID, regId);
        editor.putInt(APP_VERSION, appVersion);
        editor.commit();

       /*
        SharedPreferences.Editor editor = prefs.edit();
        editor.putString(REG_ID, regId);
        editor.putInt(APP_VERSION, appVersion);
        editor.commit();*/
    }
    public  boolean isNetworkAvailable()
    {
        ConnectivityManager connectivityManager = (ConnectivityManager)
                getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE );
        NetworkInfo activeNetInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
        boolean isConnected = activeNetInfo != null && activeNetInfo.isConnectedOrConnecting();
        if (isConnected)
            Log.i("NET", "connecte" + isConnected);
        else Log.i("NET", "not connecte" +isConnected);
        return  isConnected;
    }

}
    ---------------------------------------------------------------
    package com.appiphy.virtualnoticeboard.notification;

    import android.content.Context;
    import android.os.StrictMode;
    import java.io.IOException;
    import java.io.OutputStream;
    import java.net.HttpURLConnection;
    import java.net.MalformedURLException;
    import java.net.URL;
    import java.util.HashMap;
    import java.util.Iterator;
    import java.util.Map;

    /**
     * Created by emp005 on 23/3/16.
     */
    public class ShareExternalServer
    {
        public String shareRegIdWithAppServer(final Context context,
                                              final String regId)
        {

            String result = "";
            Map<String, String> paramsMap = new HashMap<String, String>();
            paramsMap.put("regId", regId);
            removeNetworkOnMainThread();
      //      Boolean network=mainActivity.isNetworkAvailable();
         {
                try {
                    URL serverUrl = null;
                    try {
                        //serverUrl = new URL(Config.APP_SERVER_URL);
                        serverUrl = new URL("http://192.168.1.207:8080/GCM-App-Server/GCMNotification?shareRegId=1");
                    } catch (MalformedURLException e) {
                        // Log.e("AppUtil", "URL Connection Error: " + Config.APP_SERVER_URL, e);
                        result = "Invalid URL: " + Config.APP_SERVER_URL;
                        //System.out.println("App Server Url"+ Config.APP_SERVER_URL);

                    }

                    StringBuilder postBody = new StringBuilder();
                    Iterator<Map.Entry<String, String>> iterator = paramsMap.entrySet()
                            .iterator();

                    while (iterator.hasNext())
                    {
                        Map.Entry<String, String> param = iterator.next();
                        postBody.append(param.getKey()).append('=')
                                .append(param.getValue());
                        if (iterator.hasNext())
                        {
                            postBody.append('&');
                        }
                    }
                    String body = postBody.toString();
                    byte[] bytes = body.getBytes();
                    HttpURLConnection httpCon = null;
                    try
                    {
                        httpCon = (HttpURLConnection) serverUrl.openConnection();
                        httpCon.setDoOutput(true);
                        httpCon.setUseCaches(false);
                        httpCon.setFixedLengthStreamingMode(bytes.length);
                        httpCon.setRequestMethod("POST");
                        httpCon.setRequestProperty("Content-Type",
                                "application/x-www-form-urlencoded;charset=UTF-8");
                        OutputStream out = httpCon.getOutputStream();
                        out.write(bytes);
                        out.close();
                        // System.out.println("Bytes--------1-"+bytes);
                        int status = httpCon.getResponseCode();
                        if (status == 200)
                        {
                            result = "RegId shared with Application Server. RegId: "
                                    + regId;
                        }
                        else
                        {
                            result = "Post Failure." + " Status: " + status;
                        }
                    }
                    finally
                    {
                        if (httpCon != null)
                        {
                            httpCon.disconnect();
                        }
                    }

                }
                catch (IOException e)
                {
                    result = "Post Failure. Error in sharing with App Server.";
                    // Log.e("AppUtil", "Error in sharing with App Server: " + e);
                }
            }

                return result;

        }
        public void removeNetworkOnMainThread()
        {
            // To remove Network on main thread exception
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
        }

    }

The MainActivity registers with GCM Server and the IntentService sends RegId to the server. Wi-Fi Push Notification is working well but when running on 3G network, the MainActivity screen looks like blank screen and goes in wait state. I have spent a lot of hours for that but does not get any solution.

nikita shelar
  • 51
  • 1
  • 6
  • 1
    plz see this link http://stackoverflow.com/questions/39763498/afnetworking-is-not-working-when-device-is-on-3g-network-but-its-working-when-th/39763684#39763684 – balkaran singh Oct 18 '16 at 11:40
  • check that link or add your manifest file details in your question – Madhur Oct 18 '16 at 11:42
  • Try `registerGCM` in a background thread. The issue might be that your 3g network is too slow and you are communicating with gcm server in your main thread. So code got stuck and keep waiting for the response of your `getRegistrationId()`. – Nouman Ghaffar Oct 18 '16 at 11:42
  • Also make sure your internet is working.(3g) – Nouman Ghaffar Oct 18 '16 at 11:42
  • It works currently but Server doenot get RegId shared using application can you tell why it happen – nikita shelar Oct 19 '16 at 07:20

1 Answers1

0

Have you tried testing it with different device with different Android versions? This might be a problem with the hardware or API version. Also double check if you set delayWhileIdle to true. If so, it would delay the delivery until your device is on again. [Source.]

If it doesn't work, you can try the workaround stated in this SO thread.

When you send the push notification from the server make sure to NOT include delay_while_idle, so the notification get delivered right away. Also make sure you have set time_to_live to a reasonable value (default is 4 weeks).

Community
  • 1
  • 1
abielita
  • 13,147
  • 2
  • 17
  • 59