Question

In: Computer Science

I am working on creating a Broadcast Receiver. I am extremely new to Android development and...

I am working on creating a Broadcast Receiver. I am extremely new to Android development and Java. I added my code at the bottom of this, but whenever I press the button the app crashes. I'm assuming something is wrong with connecting the broadcastIntent() function. If you could really focus on the first part that would be great!! I appreciate any help :)

Here are the directions from my professor:

  1. Create an empty project
  2. Create a method in MainActivity.java which creates a Broadcast.

public void broadcastIntent(View view){
       Intent intent = new Intent();
       intent.setAction("my.CUSTOM_INTENT"); sendBroadcast(intent);
   }

  1. Add a button to activity_main.xml and link it to this method.
  2. Is it working? How can you test it? STOP
  3. Create a Broadcast Receiver (accept defaults)
  4. Add the following code to your receiver in onReceive() : (remember to comment out the auto generated exception!) what’s an exception?
Toast.makeText(context, "Intent Detected.", Toast.LENGTH_LONG).show();
  1. Edit your manifest by adding the following as a child node of <receiver>
<intent-filter>
    <action android:name="my.CUSTOM_INTENT"></action>
</intent-filter>
  1. RUN it
MORE DIFFICULT:
  1. Create a second receiver called ConnectionReciever and add the following code in onReceive():
  2. ConnectivityManager cm =             (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);     NetworkInfo activeNetwork = cm.getActiveNetworkInfo();     boolean isConnected = activeNetwork != null &&             activeNetwork.isConnectedOrConnecting();     if (isConnected) {         try {             Toast.makeText(context, "Network is connected", Toast.LENGTH_LONG).show();         } catch (Exception e) {             e.printStackTrace();         }     } else {         Toast.makeText(context, "Network state has changed or reconnected", Toast.LENGTH_LONG).show();     } }
  3. In your manifest include the following as your intent-filter as a node of the new receiver:
<intent-filter>

    <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />

</intent-filter>
  1. Since you are being nosey – you need to ask for user- permission. Include the following as nodes of <manifest> :
<uses-permission android:name="android.permission.INTERNET" />

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
  1. Test it!

MY CODE:

<MainActivity>

package com.example.ica4_broadcast;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;


public class MainActivity extends AppCompatActivity {
    private Button mybutton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button mybutton = (Button) findViewById(R.id.mybutton);
    }

    private void broadcastIntent(View view) {
        Intent intent = new Intent();
        intent.setAction("my.CUSTOM_INTENT");
        sendBroadcast(intent);
        }

}

<activity_xml>

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/mybutton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="235dp"
        android:layout_marginEnd="146dp"
        android:layout_marginRight="146dp"
        android:onClick="broadcastIntent"
        android:text="Button"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

<manifest>

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.ica4_broadcast">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.ICA4Broadcast">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <receiver android:name=".MyReceiver" android:exported="true">
            <intent-filter>
                <action android:name="my.CUSTOM_INTENT"/>
            </intent-filter>
        </receiver>
    </application>
</manifest>

<MyReceiver>

package com.example.ica4_broadcast;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

public class MyReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
            Toast.makeText(context, "Intent Detected", Toast.LENGTH_LONG).show();

    }
}

Solutions

Expert Solution

Check this once hope it'll work fine

ThankYou

<MyReceiver>
public class MyReceiver extends BroadcastReceiver {
public MyReceiver() {
}

@@Override
public void onReceive(Context context, Intent intent) {
  
Toast.makeText(context, "Action: " + intent.getAction(), Toast.LENGTH_SHORT).show();
}
}
<AndroidManifest.xml>
<receiver android:name=".ConnectionReceiver" >
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>

<activity_main.xml>


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.journaldev.broadcastreceiver.MainActivity">

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/button"
android:text="Send Broadcast"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>

<MainActivity.java>


package com.journaldev.broadcastreceiver;

import android.content.Intent;
import android.content.IntentFilter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;

public class MainActivity extends AppCompatActivity {
ConnectionReceiver receiver;
IntentFilter intentFilter;

@@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

ButterKnife.inject(this);

receiver = new ConnectionReceiver();
intentFilter = new IntentFilter("com.journaldev.broadcastreceiver.SOME_ACTION");

}

@@Override
protected void onResume() {
super.onResume();
registerReceiver(receiver, intentFilter);

}

@Override
protected void onDestroy() {
super.onDestroy();

unregisterReceiver(receiver);
}

@@OnClick(R.id.button)
void someMethod() {

Intent intent = new Intent("com.journaldev.broadcastreceiver.SOME_ACTION");
sendBroadcast(intent);
}
}

<AndroidManifest.xml>


<?xml version="1.0" encoding="utf-8"?>
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
package="com.journaldev.broadcastreceiver">

<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:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>

<receiver android:name=".ConnectionReceiver">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>

</application>
</manifest>

<ConnectionReceiver.java >


public class ConnectionReceiver extends BroadcastReceiver {
@@Override
public void onReceive(Context context, Intent intent) {

Log.d("API123",""+intent.getAction());

if(intent.getAction().equals("com.journaldev.broadcastreceiver.SOME_ACTION"))
Toast.makeText(context, "SOME_ACTION is received", Toast.LENGTH_LONG).show();

else {
ConnectivityManager cm =
(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null &&
activeNetwork.isConnectedOrConnecting();
if (isConnected) {
try {
Toast.makeText(context, "Network is connected", Toast.LENGTH_LONG).show();
} catch (Exception e) {
e.printStackTrace();
}
} else {
Toast.makeText(context, "Network is changed or reconnected", Toast.LENGTH_LONG).show();
}
}
}

}


Related Solutions

I am working on creating a Broadcast Receiver. I am extremely new to Android development and...
I am working on creating a Broadcast Receiver. I am extremely new to Android development and Java. I added my code at the bottom. Whenever I press the button the app crashes. I'm assuming something is wrong with connecting the broadcastIntent() function. I appreciate any help :) Here are the directions from my professor: Create an empty project Create a method in MainActivity.java which creates a Broadcast. public void broadcastIntent(View view){        Intent intent = new Intent();        intent.setAction("my.CUSTOM_INTENT"); sendBroadcast(intent);...
Android Development. I am just beginning so still in the overview and brainstorming stage. The instructions...
Android Development. I am just beginning so still in the overview and brainstorming stage. The instructions are to create an app to create, track and delete memories. Memory consists of title, description, location, memory date and image. App launch should list all saved memories and option to create a new memory. Choosing the option New displays a form, has a button to access the camera and save the image as the memory image. Clicking the memory list displays the memory...
I am currently working on creating a dice game. I have not figured out how to...
I am currently working on creating a dice game. I have not figured out how to make it work? What should I do to make it work? Here is what I have so far: <!doctype html> <html> <head> <meta charset="UTF-8"> <title>Dice Game</title> <link rel="stylesheet" type="text/css" href="dice.css"> </head> <body> <div class="row" align="center"> <div class="col-4"> <h3>Your Dice</h3> <img src="dice images/m1.png" width="100" height="100" alt="roll: 1" id="mydice1"/> <img src="dice images/m1.png" width="100" height="100" alt="roll: 1" id="mydice2"/> </div> <div class="col-4"> <h3>Opponent's Dice</h3> <img src="dice images/o1.png" width="100"...
I am working on creating a Wiebull distribution from a large set of data I have....
I am working on creating a Wiebull distribution from a large set of data I have. Everything I find online says that I should be given the shape parameter (beta), and scale parameter (eta/apha). I do not have these numbers and I am not sure how to find them to accurately create a Weibull dist.
Here is the scenario that I am working on: The efficacy of a new addiction medication...
Here is the scenario that I am working on: The efficacy of a new addiction medication was evaluated in a randomized, placebo-controlled, doubleblind study. The medication in question, Antaquil, is intended to moderate the symptoms of alcohol withdrawal and craving with minimum side effects. Over the course of three weeks, a sample of 36 individuals who were recovering from alcohol addiction were randomly assigned to two groups: one administered the medication and one administered a placebo. At the end of...
Here is the scenario that I am working on: The efficacy of a new addiction medication...
Here is the scenario that I am working on: The efficacy of a new addiction medication was evaluated in a randomized, placebo-controlled, doubleblind study. The medication in question, Antaquil, is intended to moderate the symptoms of alcohol withdrawal and craving with minimum side effects. Over the course of three weeks, a sample of 36 individuals who were recovering from alcohol addiction were randomly assigned to two groups: one administered the medication and one administered a placebo. At the end of...
Here is the scenario that I am working on: The efficacy of a new addiction medication...
Here is the scenario that I am working on: The efficacy of a new addiction medication was evaluated in a randomized, placebo-controlled, doubleblind study. The medication in question, Antaquil, is intended to moderate the symptoms of alcohol withdrawal and craving with minimum side effects. Over the course of three weeks, a sample of 36 individuals who were recovering from alcohol addiction were randomly assigned to two groups: one administered the medication and one administered a placebo. At the end of...
Here is the scenario that I am working on: The efficacy of a new addiction medication...
Here is the scenario that I am working on: The efficacy of a new addiction medication was evaluated in a randomized, placebo-controlled, doubleblind study. The medication in question, Antaquil, is intended to moderate the symptoms of alcohol withdrawal and craving with minimum side effects. Over the course of three weeks, a sample of 36 individuals who were recovering from alcohol addiction were randomly assigned to two groups: one administered the medication and one administered a placebo. At the end of...
Scenario: I am creating a course for inclusion into an established nursing curriculum. I am supposed...
Scenario: I am creating a course for inclusion into an established nursing curriculum. I am supposed to describe the program level of the course am proposing. What do they mean by program level? This is a hypothetical community college with a two year nursing program.
Hello, I am working on an assignment but I am unsure of how to solve it....
Hello, I am working on an assignment but I am unsure of how to solve it. Please help me. The assignment details are below. Consider this scenario: Your friend starts a website, nothingbutflags.com, which is not making money. Your friend asks you to help generate more traffic. You ask your friend how much traffic the website had last month? And your friend replies and says only 500 visits. You also ask how many flags did you sell? Your friend replies...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT