0

Explanation: I made this intent service in a new class (connectionchecker.java) which is used to check for internet connection. Now in my main class (First.java), the values are not recieved because the if() is never executed. My app doesn't crash, the problem is the TextView is stuck on "CONNECTION:" instead of saying "CONNECTION:You are not connected to the internet." or ""CONNECTION:You are not connected to the internet.".

Code: First.java

package com.lofty.lofti;

import com.lofty.lofti.util.SystemUiHider;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.inputmethodservice.Keyboard;
import android.inputmethodservice.KeyboardView.OnKeyboardActionListener;
import android.view.KeyEvent;
import android.view.View.OnKeyListener;
import android.inputmethodservice.KeyboardView;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.content.BroadcastReceiver;

/**
 * An example full-screen activity that shows and hides the system UI (i.e.
 * status bar and navigation/system bar) with user interaction.
 *
 * @see SystemUiHider
 */
public class First extends Activity {
    /**
     * Whether or not the system UI should be auto-hidden after
     * {@link #AUTO_HIDE_DELAY_MILLIS} milliseconds.
     */
    private static final boolean AUTO_HIDE = true;

    /**
     * If {@link #AUTO_HIDE} is set, the number of milliseconds to wait after
     * user interaction before hiding the system UI.
     */
    private static final int AUTO_HIDE_DELAY_MILLIS = 3000;

    /**
     * If set, will toggle the system UI visibility upon interaction. Otherwise,
     * will show the system UI visibility upon interaction.
     */
    private static final boolean TOGGLE_ON_CLICK = true;

    /**
     * The flags to pass to {@link SystemUiHider#getInstance}.
     */
    private static final int HIDER_FLAGS = SystemUiHider.FLAG_HIDE_NAVIGATION;

    /**
     * The instance of the {@link SystemUiHider} for this activity.
     */
    private SystemUiHider mSystemUiHider;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getActionBar().hide(); // HIDE ACTION BAR.
        setContentView(R.layout.activity_first);




        EditText enter = (EditText) findViewById(R.id.searchbox);
        enter.setOnKeyListener(new OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_ENTER) {
                    EditText searchbox = (EditText) findViewById(R.id.searchbox);
                    String search = searchbox.getText().toString();
                    Intent open = new Intent(Intent.ACTION_WEB_SEARCH);
                    open.putExtra(SearchManager.QUERY, search);
                    startActivity(open);
                    return true;
                }
                else
                {
                    return false;
                }
            }
        });
    }

    public class Connection extends BroadcastReceiver
    {
        @Override
        public void onReceive(Context context, Intent intent) {
            Integer connectionn = intent.getIntExtra("connection",0);
            TextView connectiontext = (TextView) findViewById(R.id.connectiontext);

            if(connectionn==1)
            {
                    connectiontext.setText("CONNECTION:You are not connected to the internet.");
            }
            if(connectionn==0)
            {
                    connectiontext.setText("CONNECTION:You are not connected to the internet.");

            }
        }
    }

    public void exit(View view)
     {
         finish();
         System.exit(0);
     }

    public void usernameclick (View view)
    {
        EditText searchbox = (EditText) findViewById(R.id.searchbox);
        String search = searchbox.getText().toString();
        Intent open = new Intent(Intent.ACTION_WEB_SEARCH);
        open.putExtra(SearchManager.QUERY, search);
        startActivity(open);

    }


}

connectionchecker.java

package com.lofty.lofti;

import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.widget.EditText;

public class connectionchecker extends IntentService
{
    public static final int connection =0;

    public connectionchecker() {
        super("connectionchecker");

    }

    @Override
    protected void onHandleIntent(Intent intent) {
        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|| connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_ETHERNET).getState()== NetworkInfo.State.CONNECTED)

        {

            Intent data = new Intent(this, First.class);
            data.putExtra("connection",1);
            sendBroadcast(data);
        }
        else
        {
            Intent data = new Intent(this, First.class);
            data.putExtra("connection", 0 );
            sendBroadcast(data);
        }
    }
}

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.lofty.lofti" >
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >

        <activity
            android:name=".First"
            android:configChanges="orientation|keyboardHidden|screenSize"
            android:label="@string/app_name"
            android:theme="@style/FullscreenTheme" >

            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service android:name=".connectionchecker"/>
        <receiver android:name=".First$Connection"/>
    </application>


</manifest>

Thank you and have a good day.

Logcat:

10-23 16:01:25.765    2175-2175/com.lofty.lofti E/Zygote﹕ MountEmulatedStorage()
10-23 16:01:25.765    2175-2175/com.lofty.lofti E/Zygote﹕ v2
10-23 16:01:25.775    2175-2175/com.lofty.lofti I/SELinux﹕ Function: selinux_compare_spd_ram, SPD-policy is existed. and_ver=SEPF_GT-I9505_5.0.1 ver=27
10-23 16:01:25.775    2175-2175/com.lofty.lofti I/SELinux﹕ Function: selinux_compare_spd_ram , priority [2] , priority version is VE=SEPF_GT-I9505_5.0.1-1_0032
10-23 16:01:25.775    2175-2175/com.lofty.lofti E/SELinux﹕ [DEBUG] get_category: variable seinfo: default sensitivity: NULL, cateogry: NULL
10-23 16:01:25.775    2175-2175/com.lofty.lofti I/art﹕ Late-enabling -Xcheck:jni
10-23 16:01:25.955    2175-2175/com.lofty.lofti D/ResourcesManager﹕ creating new AssetManager and set to /data/app/com.lofty.lofti-2/base.apk
10-23 16:01:26.185    2175-2175/com.lofty.lofti D/AndroidRuntime﹕ Shutting down VM
10-23 16:01:26.195    2175-2175/com.lofty.lofti E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.lofty.lofti, PID: 2175
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.lofty.lofti/com.lofty.lofti.First}: java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity.
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2693)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2758)
            at android.app.ActivityThread.access$900(ActivityThread.java:177)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1448)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:145)
            at android.app.ActivityThread.main(ActivityThread.java:5942)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1400)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1195)
     Caused by: java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity.
            at android.support.v7.app.AppCompatDelegateImplV7.createSubDecor(AppCompatDelegateImplV7.java:309)
            at android.support.v7.app.AppCompatDelegateImplV7.ensureSubDecor(AppCompatDelegateImplV7.java:278)
            at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:252)
            at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:109)
            at com.lofty.lofti.First.onCreate(First.java:68)
            at android.app.Activity.performCreate(Activity.java:6289)
            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2758)
            at android.app.ActivityThread.access$900(ActivityThread.java:177)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1448)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:145)
            at android.app.ActivityThread.main(ActivityThread.java:5942)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1400)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1195)
10-23 16:06:26.538    2175-2175/? I/Process﹕ Sending signal. PID: 2175 SIG: 9

2 Answers2

0

I just update your code, by following the tuto from Lars http://www.vogella.com/tutorials/AndroidBroadcastReceiver/article.html

  1. You have to register the broadcast receiver before it can receive anything. Have a look at this question. https://stackoverflow.com/a/4806091/2733216

    IntentFilter filter = new IntentFilter(Connection.ACTION_RESP);
    registerReceiver(mConnection, filter);
    
  2. Your service wasn't started (at least in the code you provided)

    in your Activity 'onCreate'

    // Start your Service
    Intent msgIntent = new Intent(this, ConnectionChecker.class);
    startService(msgIntent);
    
  3. You didn't instantiate your BroadCastReceiver

    // Instanciate your BCR
    mConnection = new Connection();
    
  4. Define a message :

    public static final String ACTION_RESP = "intent.action.MESSAGE_PROCESSED";
    
  5. Define the message to the Intent

    data.setAction(MainActivity.Connection.ACTION_RESP);
    
  6. Use Default Intent Constructor for the one that are sent from the Service

    Intent data = new Intent();
    

Then finally, the whole code :

  1. Activity

    public class MainActivity extends AppCompatActivity {

    private Connection mConnection;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    
    
    
        EditText enter = (EditText) findViewById(R.id.searchbox);
        enter.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_ENTER) {
                    EditText searchbox = (EditText) findViewById(R.id.searchbox);
                    String search = searchbox.getText().toString();
                    Intent open = new Intent(Intent.ACTION_WEB_SEARCH);
                    open.putExtra(SearchManager.QUERY, search);
                    startActivity(open);
                    return true;
                } else {
                    return false;
                }
            }
        });
    
        // Start your Service
        Intent msgIntent = new Intent(this, ConnectionChecker.class);
        startService(msgIntent);
    
        // Instanciate BCR
        mConnection = new Connection();
        // Register BCR
        IntentFilter filter = new IntentFilter(Connection.ACTION_RESP);
        registerReceiver(mConnection, filter);
    
    }
    
    public class Connection extends BroadcastReceiver {
        public static final String ACTION_RESP = "intent.action.MESSAGE_PROCESSED";
    
        @Override
        public void onReceive(Context context, Intent intent) {
            Integer connectionn = intent.getIntExtra("connection", 0);
            TextView connectiontext = (TextView) findViewById(R.id.connectiontext);
    
            if (connectionn == 1)
                connectiontext.setText("CONNECTION:You are not connected to the internet.");
            else
                connectiontext.setText("CONNECTION:You are not connected to the internet.");
    
        }
    }
    
    public void exit(View view) {
        finish();
        System.exit(0);
    }
    
    public void usernameclick(View view) {
        EditText searchbox = (EditText) findViewById(R.id.searchbox);
        String search = searchbox.getText().toString();
        Intent open = new Intent(Intent.ACTION_WEB_SEARCH);
        open.putExtra(SearchManager.QUERY, search);
        startActivity(open);
    
    }
    

    }

  2. Service

    public class ConnectionChecker extends IntentService { public static final int connection =0;

    public ConnectionChecker() {
        super("connectionchecker");
    
    }
    
    @Override
    protected void onHandleIntent(Intent intent) {
        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|| connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_ETHERNET).getState()== NetworkInfo.State.CONNECTED)
    
        {
    
            Intent data = new Intent();
            data.setAction(MainActivity.Connection.ACTION_RESP);
            data.putExtra("connection", 1);
            sendBroadcast(data);
    
    
        }
        else
        {
            Intent data = new Intent();
            data.setAction(MainActivity.Connection.ACTION_RESP);
            data.putExtra("connection", 0 );
            sendBroadcast(data);
        }
    }
    

    }

Community
  • 1
  • 1
Anthony
  • 3,989
  • 2
  • 30
  • 52
  • I read that page many times but it's not clear enough for me :/ if you have the code answer for my issue please post it and I will try my best to understand – James Jackson Oct 23 '15 at 11:19
  • I inspected and put the code you gave me in android studio, no errors while compuling but the apps now crashes **upon start-up**. Here's the logcat: http://pastebin.com/39RRmYsd First.java : http://pastebin.com/xtgJMKQK connectionchecker.java : http://pastebin.com/8RMrTrBK I've put the codes there since you can't add them here, too many chars – James Jackson Oct 23 '15 at 15:04
  • Ok, ill add it to my first post. – James Jackson Oct 23 '15 at 15:07
  • This is just a theme issue, just extends from Activity and not from AppCompActivity – Anthony Oct 23 '15 at 15:51
  • add this `@Override protected void onStop() { unregisterReceiver(mConnection); super.onStop(); }`in your activity – Anthony Oct 23 '15 at 16:46
  • but there is another issue about the network info that is not about what we are chatting : `java.lang.NullPointerException: Attempt to invoke virtual method 'android.net.NetworkInfo$State android.net.NetworkInfo.getState()' on a null object reference at com.lofty.lofti.connectionchecker.onHandleIntent(connectionchecker.java:21)` – Anthony Oct 23 '15 at 16:47
  • The issues were with the deprecated getNetworkInfo , I switched it up to getActiveNetworkInfo and it's working now ! Messages are working properly ! Now if I want to make the service (connectionchecker) happen lets say every 5 seconds after onCreate, how should I set up the loop in your opinion? and then break the loop once the application is paused/destroyed. Thanks a lot bro ! – James Jackson Oct 23 '15 at 17:11
0

the values are not received because the if() is never executed

Pass an action for the Intent, instead of using like this:

Intent data = new Intent(this, First.class);

But, you should:

Intent data = new Intent("ACTION_NAME");

And make sure that you registered that action to manifest:

<receiver android:name=".First$Connection">
    <intent-filter>
        <action android:name="ACTION_NAME" />
    </intent-filter>
</receiver>

the problem is the TextView is stuck

Make an instance variable for connectiontext:

public class First extends Activity {

    ...
    private TextView connectiontext;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_first);
        getActionBar().hide(); // HIDE ACTION BAR.
        connectiontext = (TextView) findViewById(R.id.connectiontext);
        ...
    }
...
}
Anggrayudi H
  • 14,977
  • 11
  • 54
  • 87
  • which action should I use? ACTION_RESP ? – James Jackson Oct 23 '15 at 15:10
  • @JamesJackson, the action's name is up to you. You don't need to use `ACTION_RESP`. But remember that you have to give the same name to manifest as I described above. – Anggrayudi H Oct 23 '15 at 15:15
  • Okay so I did what you told me, the TextView is still "Connection:" :/ First.java http://pastebin.com/xjXTsVm4 connectionchecker.java: http://pastebin.com/S87CFxwG AndroidManifest.xml: http://pastebin.com/mUUf8FRa Do you want the logcat too? – James Jackson Oct 23 '15 at 15:31
  • @JamesJackson, why don't you use `boolean connected = intent.getBooleanExtra("connection", false);` and send it through `data.putExtra("connection", true);`? Also, use `Intent data = new Intent("ACTION_NAME");` – Anggrayudi H Oct 23 '15 at 15:34
  • alright I did everything you said and the textview is still not changing, I added an Intent in onCreate to start the service which is now making the app crash. – James Jackson Oct 23 '15 at 15:58
  • @JamesJackson, your error is refers to http://stackoverflow.com/q/21814825/3922207. Please read. – Anggrayudi H Oct 23 '15 at 16:12
  • The issues were with the deprecated getNetworkInfo , I switched it up to getActiveNetworkInfo and it's working now ! Messages are working properly ! Now if I want to make the service (connectionchecker) happen lets say every 5 seconds after onCreate, how should I set up the loop in your opinion? and then break the loop once the application is paused/destroyed. Thanks a lot bro ! – James Jackson Oct 23 '15 at 17:16