Unable to get Broadcast - java

I am unable to receive broadcast intent, although I have registered it . Can you please spot the error. Thank you very much. I tried with log messages, but it never reached onReceive() of broadcast receiver class.
Here is Class from which I send Broadcast
public class ServiceDemoActivity extends Activity {
Button startButton,stopButton,pauseButton;
final String musicIntentAction="com.CompetenceProject.Musicfilter";
Intent musicIntent=new Intent();
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
startButton=(Button)findViewById(R.id.startButton);
stopButton=(Button)findViewById(R.id.Stopbutton);
pauseButton=(Button)findViewById(R.id.Pausebutton);
musicIntent.setAction(musicIntentAction);
startButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.w("DEBUG", "Came to StartButton");
musicIntent.putExtra("Message","start");
sendBroadcast(musicIntent);
Toast.makeText(getApplicationContext(), "starBroadcaseSent",1000).show();
}
});
stopButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.w("DEBUG", "Came to StopButton");
musicIntent.putExtra("Message","stop");
sendBroadcast(musicIntent);
Toast.makeText(getApplicationContext(), "stopBroadcaseSent",1000).show();
}
});
pauseButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.w("DEBUG", "Came to PauseButton");
musicIntent.putExtra("Message","pause");
sendBroadcast(musicIntent);
Toast.makeText(getApplicationContext(), "PauseBroadcaseSent",1000).show();
}
});
}
}
Here is Class that listens to broadcast:
public class MusicBroadcsatListener extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
Log.w("DEBUG", "Came to BroadCast OnRecieve");
Bundle extras = intent.getExtras();
String res=extras.getString("Message");
Toast.makeText(context, "Intent Extra is "+res, 1000).show();
Log.v("BroadCase","true");
System.out.println("Broadcast came here");
if(res.equalsIgnoreCase("start"))
Toast.makeText(context, "start", 1000).show();
else if(res.equalsIgnoreCase("pause"))
Toast.makeText(context, "pause", 1000).show();
else if (res.equalsIgnoreCase("stop"))
Toast.makeText(context, "stop", 1000).show();
}
}
This is the Androidmanifest:
<activity
android:label="#string/app_name"
android:name=".ServiceDemoActivity" >
<intent-filter >
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<receiver android:name=".MusicBroadcsatListener" android:enabled="true">
<intent-filter>
<action android:name="com.CompetenceProject.Musicfilter"></action>
</intent-filter>
</receiver>
Thank you.

First thing I would do is check this typo you have in your Manifest.xml file. I can't see the name of your receiver class here, but if its name has "broadcast" in it, you spelled "broadcast" wrong -- "MusicBroadcsatListenter" -- in your manifest.xml file:
<receiver android:name=".MusicBroadcsatListener" android:enabled="true">

To test, you have to execute the broadcast receiver before you execute the activity -- on the same device -- because the receiver needs to be running. I'm not sure the best way to do this, but out of curiosity I copied and pasted your code into Eclipse into two separate projects -- one for the receiver and one for the activity. I executed the receiver project, then the activity project, and your code worked fine. If someone has a better way to test this, please post as I'd like to know too.

I found the solution by myself. I had put the receiver inside the activity tag. Thank you all for the support.

Related

Broadcast receiver not working when app is closed

So I have two different apps made, one sends a broadcast and another receives it and displays a toast. However, when I close the receiver app the broadcast is no longer received by the second app even though I defined the receiver in the manifest file.
The broadcast sender in the MainActivity of app1.
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button b = (Button)findViewById(R.id.button2);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent();
i.setAction("com.example.ali.rrr");
i.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
sendBroadcast(i);
Log.e("Broadcast","sent");
}
});
}
App 2 broadcast receiver:
public class MyReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// TODO: This method is called when the BroadcastReceiver is receiving
// an Intent broadcast.
Toast.makeText(context, "Broadcast has been recieved!", Toast.LENGTH_SHORT).show();
Log.e("SUCCESS", "IN RECIEVER");
//throw new UnsupportedOperationException("Not yet implemented");
}
App 2s Manifest:
<?xml version="1.0" encoding="utf-8"?>
<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/AppTheme">
<receiver
android:name=".MyReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="com.example.ali.rrr" />
</intent-filter>
</receiver>
<activity
android:name=".MainActivity"
android:label="#string/title_activity_main"
android:theme="#style/AppTheme.NoActionBar" />
<activity
android:name=".Main2Activity"
android:label="#string/title_activity_main2"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
After registering my BroadcastReceiver (BR) statically in the manifest, applying the proper intent filters, using JobIntentService (and registering it in the manifest) to handle the work that was called from my BR, I was still getting inconsistent results.
Once all of what I listed above has been done you should be able to send an ADB command to activate your broadcast and process the work in your service even if the app is closed. This was working for me some of the time, but not all of the time.
This article describes limitation to BRs.
"As of Android 3.1 the Android system excludes all receiver from receiving intents by default if the corresponding application has never been started by the user or if the user explicitly stopped the application via the Android menu" (AKA a user executes Force Stop)
When I start the app by debugging it, then swipe it closed on my device, my ADB command never activates my BR. However, after my debugging session is over, when I open up the app on my device and swipe it closed, I can activate my BR through ADB commands.
This occurs because when you debug an application, then manually swipe it closed on the device, Android considers this a Force Stop hence why my BR cannot be activated until I re-open the app on the device without debugging.
Scoured the internet for hours, and wasn't able to find my solution, so I thought I'd post it here just in case some poor unfortunate soul is encountering the same weird functionality I was.
Happy coding :)
First of all you need to use the Service for this functionality to work.
In the Activity you can start and stop the service by using the below codes.
// to start a service
Intent service = new Intent(context, MyBrodcastRecieverService.class);
context.startService(service);
// to Stop service
Intent service = new Intent(context, MyBrodcastRecieverService.class);
context.stopService(service);
Then you can use the below service
public class MyBrodcastRecieverService extends Service
{
private static BroadcastReceiver br_ScreenOffReceiver;
#Override
public IBinder onBind(Intent arg0)
{
return null;
}
#Override
public void onCreate()
{
registerScreenOffReceiver();
}
#Override
public void onDestroy()
{
unregisterReceiver(br__ScreenOffReceiver);
m_ScreenOffReceiver = null;
}
private void registerScreenOffReceiver()
{
br_ScreenOffReceiver = new BroadcastReceiver()
{
#Override
public void onReceive(Context context, Intent intent)
{
Log.d(TAG, "ACTION_SCREEN_OFF");
// do something, e.g. send Intent to main app
}
};
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_OFF);
registerReceiver(br_ScreenOffReceiver, filter);
}
}
I faced this issue recently. The BroadcastReceiver was working fine even if the app was removed from the background in the emulator and Samsung phones. But it failed to start my app in Chinese manufactured phones like Realme, Mi etc. While struggling to find a way to fix this I found that in the app details page there is battery optimisation settings where the Auto-launch feature was disabled. After I enabled it the app was working fine and BroadcastReceiver was able to start the app. I was unable ti find a way to enable this setting programmatically but I found this question which helped me direct the user to that setting page.
You can go through below solution;
Activity.java
Intent intent=new Intent(MainActivity.this,BroadcastService.class);
startService(intent);
BroadcastService.java
public class BroadcastService extends Service {
private static MusicIntentReceiver br_ScreenOffReceiver;
#Override
public IBinder onBind(Intent arg0)
{
return null;
}
#Override
public void onCreate()
{
registerScreenOffReceiver();
}
#Override
public void onDestroy()
{
}
private void registerScreenOffReceiver()
{
br_ScreenOffReceiver = new MusicIntentReceiver()
{
#Override
public void onReceive(Context context, Intent intent)
{
if (intent.getAction().equals(Intent.ACTION_HEADSET_PLUG)) {
int state = intent.getIntExtra("state", -1);
switch (state) {
case 0:
Log.e("AAAAAAAAAA", "Headset is unplugged");
break;
case 1:
Log.e("AAAAAAAAA", "Headset is plugged");
break;
default:
Log.e("AAAAAAAAAAAA", "I have no idea what the headset state is");
}
}
}
};
IntentFilter filter = new IntentFilter(Intent.ACTION_HEADSET_PLUG);
registerReceiver(br_ScreenOffReceiver, filter);
}
}
Menifest
<service android:enabled="true" android:name=".BroadcastService" />
Try this way..
Intent i = new Intent();
i.setAction("com.example.ali.rrr");
i.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
i.setComponent(
new ComponentName("PackageNameApp2","PackageNameApp2.MainActivity"));
sendBroadcast(i);

How can i change incoming call screen of phone in java?

I want to change incoming call screen to my own layout. I used a sample to do this for me. but it sometimes appear(when calling) and sometimes not. I do not know how to solve this problem that my own layout appear every time.
This is my codes.
public class PhoneStateReceiver extends BroadcastReceiver {
#Override
public void onReceive(final Context context, Intent intent) {
Intent i = new Intent();
i.setClass(context, MainActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
}
and this is the manifest.
<receiver android:name="com.example.changescreen.PhoneStateReceiver">
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE" />
</intent-filter>
</receiver>
Try adding a delay before starting your activity.
The Problem is your activity is being overlapped by the default activity

How to exit of program on android

How to exit from my app on button click in Android app?
I've tried button click event method. Tell me the code or logic for it.
java file:
Button button;
button=(Button) findViewById(R.id.exit);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
}
});
Just make a finish(); as follows :
Button button;
button=(Button) findViewById(R.id.exit);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
What does finish() do?
Call this when your activity is done and should be closed. The ActivityResult is propagated back to whoever launched you via onActivityResult().
For more information read the finish() documentation
EDIT
Add this on your manifest.xml file :
<activity
android:autoRemoveFromRecents="true"/>
If you want to avoid finish(); just call an Intent like this :
Intent i = new Intent(Intent.ACTION_MAIN);
i.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
i.addCategory(Intent.CATEGORY_HOME);
startActivity(i);
EDIT with sample
My manifest.xml
<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"
android:excludeFromRecents="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
My setOnClickListener()
btn = (Button)findViewById(R.id.button);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent1 = new Intent(Intent.ACTION_MAIN);
intent1.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
intent1.addCategory(Intent.CATEGORY_HOME);
startActivity(intent1);
//finish(); it can also be done
}
});
#Override
public void onClick(View paramView)
{
finish();
moveTaskToBack(true);
}
In Android is not recommended to close/kill applications, because that is already done by OS automatically when needed. As #33go user already recommended, calling finish() in your application should be enough. But if you really want to stop the process in an easy way you can try this, from everywhere in your app:
System.exit(0);
try
android.os.Process.killProcess(android.os.Process.myPid());
Just try to double back press to exit your application. Paste this code to your activity:
private static long back_pressed;
#Override
public void onBackpressed()
{
if (back_pressed + 2000 > System.currentTimeMillis()) {
super.onBackPressed();
} else {
Toast.makeText(getBaseContext(), "Press once again to exit!", Toast.LENGTH_SHORT).show();
}
this.back_pressed = System.currentTimeMillis();
}

Intent issue (display new form) Android

Ok I've been looking around for hours. I've tried just about everything and I'm not sure what is going on but I'm getting the issue where it can't find the activity. The activity is in my manifest file. I've tried with .ActivityName and com...ActivityName. I've saved, I've cleaned, I've closed/opened eclipse. It just can't seem to find it. Here's code, maybe I'm missing something?
Manifest file:
<activity android:name=".Activity2"></activity>
Listener in MainActivity:
View.OnClickListener test = new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,Activity2.class);
startActivity(intent);
}
};
Activity2:
public class Activity2 extends Activity {
ImageButton btnTest;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// TODO Auto-generated method stub
btnTest= (ImageButton)findViewById(R.id.btnDepressed);
btnTest.setOnClickListener(GoTest);
}
...etc.
I've read so many articles on this from here and other sites. I've watched videos.. I simply don't see what I'm doing wrong. The activity is defined in the manifest, I've tried the intent with the above code, as well as with:
new Intent("com.blah.blah.Activity2");
Neither is working. Any ideas?
try this
<activity android:name=".Activity2"
android:label="#string/app_name">
<intent-filter>
<action android:name="com.blah.blah.Activity2" />
</intent-filter>
</activity>
from activity code you have to do some thing like this
Intent intent = new Intent();
intent.setAction("com.blah.blah.Activity2");
intent.addCategory(Intent.CATEGORY_DEFAULT);
startActivity(intent);`
Check your package com.blah.blah for Activity2.
Inside your AndroidManifest.xml you should define your package as:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.blah.blah"
...
And define your activity as:
<activity
android:name="com.blah.blah.Activity2">
</activity>
OR
<activity
android:name=".Activity2">
</activity>

Can't switch between activities

sorry for asking dumb questions, java and Android are both new to me ;)
My problem: I can't switch between two activities in a very simple app. I tried solutions described in similar topics but it didn't work.
So this is my 1st Activity (I didn't paste the imports):
public class OneActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void OnStart(){
Button Btn = (Button)findViewById(R.id.btnNext);
Btn.setOnClickListener(new OnClickListener() {
public void onClick(View Button) {
Intent myIntent = new Intent(OneActivity.this, UserInput.class);
OneActivity.this.startActivity(myIntent);
}
});
}
}
The second Activity is very simple - it is just supposed to load a layout called userinput.xml:
public class UserInput extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.userinput);
}
}
The application part of the Manifest looks like following:
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<activity
android:name=".OneActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<activity
android:name=".UserInput"
android:label="#string/app_name" />
</activity>
</application>
When I run the app and click the button nothing happens. Where could be the problem?
// Alright, I have put the code into the onCreate() method so it now looks like following:
public class OneActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button Btn = (Button)findViewById(R.id.btnNext);
Btn.setOnClickListener(new OnClickListener() {
public void onClick(View Button) {
Intent myIntent = new Intent(OneActivity.this, UserInput.class);
OneActivity.this.startActivity(myIntent);
}
});
}
}
Now the app crashes (force close) anytime I click the Next button.
You define your onStart() function with a capital 'O'. That is why the function is never called.
Your onStart():
public void OnStart(){ ... }
How it should be:
// Note the lowercase 'o' in onStart
public void onStart(){ ... }
Also note that having an #Override above the function name when you want to override a method will help prevent making these mistakes, as Eclipse (or whatever IDE you use) will tell you that you are not actually overriding a function.
Write below code in onCreate() method:
Button Btn = (Button)findViewById(R.id.btnNext);
Btn.setOnClickListener(new OnClickListener() {
public void onClick(View Button) {
Intent myIntent = new Intent(OneActivity.this, UserInput.class);
startActivity(myIntent);
}
});
2nd correction for android manifest file:
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<activity
android:name=".OneActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity> <!-- closed here -->
<activity
android:name=".UserInput"
android:label="#string/app_name" />
</application>
You can move all the code in onCreate() and simplify like this
startActivity(new Intent(this, UserInput.class));
But I don't understand why you start another activity like this
Check it following line
Intent myIntent = new Intent(OneAvtivity.this, SecondActivity.class);
startActivity(myIntent);
Your Class name is UserIpnout and you write SecondActivity.class
Intent myIntent = new Intent(OneAvtivity.this, UserInput .class);
startActivity(myIntent);

Categories