I am trying to make broadcast receiver which will show a toast message when user click on button from my another app activity.
But receiver not showing result.
My code is below
My Receiver App
MyReceiver:
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, "Broadcast has been received!", Toast.LENGTH_LONG).show();
}
}
Manifest:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.xyz.receivebroadcast">
<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.xyz.broadcasts"></action>
</intent-filter>
</receiver>
</application>
My sender app
My MainActivity which sends the broadcasts is here.
MainActivity:
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void SendOutBroadcast(View view){
Intent i = new Intent();
i.setAction("com.example.xyz.broadcasts");
i.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
sendBroadcast(i);
}
}
activity_main.xml:
<android.support.constraint.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="com.example.xyz.broadcasts.MainActivity">
<Button
android:id="#+id/sendButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="SendOutBroadcast"
android:text="Send Broadcast"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
In your case your activity Intent should be like this:
Intent intent = new Intent();
intent.setAction("com.example.xyz.broadcasts");
intent.putExtra("KeyName","code1id");
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
intent.setComponent(
new ComponentName("com.pkg.AppB","com.pkg.AppB.MainActivity"));
sendBroadcast(intent);
Try this may help you or visit for more information.
NOTE - This may be not going to work in Android O because in Android O implicit broadcast are ban as mentioned Here. (Also credits to you #Muhammad Arslan Maqsood)
i found the issue: issue is not with code, actually Android O disabled the feature "Implicit broasdcast". see this
Related
Hello i tried many times when i click the button it doesn't show the toast and broadcast receiver
the code attached down there kindly correct my miss takes its run successfully but when click the button nothing happend at all , I tried to edit in activity_main.xml but nothing happend
MainActivity.java
package com.example.myapplication;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
// broadcast a custom intent.
public void broadcastIntent(View view){
Intent intent = new Intent();
intent.setAction("com.myapplication.BOOT_COMPLETED"); sendBroadcast(intent);
}
}
MyReceiver.java
package com.example.myapplication;
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();
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myapplication">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true">
<activity android:name=".MainActivity"
android:exported="true">
<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="false">
<intent-filter>
<action android:name="com.myapplication.BOOT_COMPLETED">
</action>
</intent-filter>
</receiver>
</application>
</manifest>
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Example of Broadcast"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:textSize="30dp" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tutorials point "
android:textColor="#ff87ff09"
android:textSize="30dp"
android:layout_above="#+id/imageButton"
android:layout_centerHorizontal="true"
android:layout_marginBottom="40dp" />
<ImageButton
android:id="#+id/imageButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:minWidth="48dp"
android:minHeight="48dp"
tools:ignore="SpeakableTextPresentCheck" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/imageButton"
android:layout_centerHorizontal="true"
android:onClick="broadcastIntent"
android:text="broadcast_intent" />
</RelativeLayout>
I hope this could help
import androidx.appcompat.app.AppCompatActivity;
import android.content.BroadcastReceiver;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends AppCompatActivity {
BroadcastReceiver br;
IntentFilter filter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
br = new MyReceiver();
filter= new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
filter.addAction(Intent.ACTION_AIRPLANE_MODE_CHANGED);
}
public void broadcastIntent(View view){
Intent intent = new Intent();
intent.setAction("com.myapplication.BOOT_COMPLETED");
sendBroadcast(intent);
this.registerReceiver(br, filter);
}
}
also see this link
https://developer.android.com/guide/components/broadcasts
You are using a Manifest-declared receiver. This receiver would get invoked outside from other app or with some system events.
The receiver then becomes a separate entry point into your app which means that the system can start the app and deliver the broadcast if the app is not currently running.
If you want to trigger this receiver within the app you should register this receiver. In your case inside the MainActivity within onCreate or onResume as follows
broadcastReceiver = new MyReceiver ()
Intent filter = new IntentFilter("com.myapplication.BOOT")
registerReceiver(broadcastReceiver, filter)
Also you need to unregister it within onDestroy or onPause
unregisterReceiver(broadcastReceiver)
I guess you should use Context-registered receiver for your use case where you want to send a broadcast within the app. Its almost the same except that you don't need to define it inside the manifest.
More information here
Activities:
MainActivity (Splash Screen)
MainActivity2 (Login)
SignupActivity (Signup)
MainActivity3 (Registering details)
ChatActivity (Hide on quiting from here)
Basically what i am trying to accomplish i i wanna hide my app after i do the initial signup part which will be handled uptill MainActivity3 and then when the user quits from the app the app icon should disappear and must only appear when called from dialer. My BroadcastReciever class never gets triggered,I am unable to figure out where i am going wrong Thanks in advance.
BroadCastReceiver.class
package com.insignia.socialmediasim;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.util.Log;
public class MyBroadCastReciever extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
String ourCode = "**1234";
String dialedNumber = getResultData();
Log.d("triggered", "onReceive: "+dialedNumber);
if ((dialedNumber.equals(ourCode))){
// My app will bring up, so cancel the dialer broadcast
setResultData(null);
PackageManager packageManager = context.getPackageManager();
ComponentName componentName = new ComponentName(context, com.insignia.socialmediasim.MainActivity.class);
packageManager.setComponentEnabledSetting(componentName,PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);
//Intent to launch MainActivity
Intent intent_to_mainActivity = new Intent(context, MainActivity.class);
context.startActivity(intent_to_mainActivity);
}
}}
ChatActivity.class, "This is the class in which i hide my app"
package com.insignia.socialmediasim;
import androidx.appcompat.app.AppCompatActivity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;
public class ChatActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_chat);
Intent intent = getIntent();
Toast.makeText(ChatActivity.this, "Welcome Back to the adobe " + intent.getStringExtra("type"), Toast.LENGTH_LONG).show();
}
#Override
protected void onStop() {
super.onStop();
PackageManager packageManager = getPackageManager();
ComponentName componentName = new ComponentName(ChatActivity.this, com.insignia.socialmediasim.MainActivity.class);
packageManager.setComponentEnabledSetting(componentName,PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP);
}}
AndroidManifest.XML
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.insignia.socialmediasim">
<uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS" />
<application
android:allowBackup="true"
android:icon="#mipmap/asd"
android:label="#string/appnameda"
android:roundIcon="#mipmap/asd"
android:supportsRtl="true"
android:theme="#style/Theme.Design.NoActionBar">
<activity android:name=".ChatActivity" />
<activity android:name=".MainActivity3" />
<activity android:name=".SignupActivity" />
<activity android:name=".MainActivity2" />
<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=".MyBroadCastReciever">
<intent-filter>
<action android:name="android.intent.action.NEW_OUTGOING_CALL" />
</intent-filter>
</receiver>
</application>
It is recommended that register and unregister the broadcast programmatically in you activity.Try It.
this is a sample code for registering a broadcastReceiver:
IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
filter.addAction(Intent.ACTION_AIRPLANE_MODE_CHANGED);
this.registerReceiver(br, filter);
You can check more information from this document: broadcasts
i was trying to create my own alarm clock in android. The aim is that my alarm clock should play different songs based on my playlist . This is a college project . User sets an alarm and then forgets and then even after multiple restarts the alarm should play . I downloaded a sample code from and was working on this . However on a restart of phone my alarms are getting lost . I found that i need to use broadcast receiver but still its not working on my phone lava phone . Can you please suggest if this code is fine . Here is my code link:https://drive.google.com/file/d/1ADVyH0grEQ4g80HkFU1n2Cb4wxnQC4TX/view?usp=sharing
my android manifest file is..
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.alarmmanager">
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<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">
<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="MyBroadcastReceiver" >
</receiver>
</application>
</manifest>
my layout file...
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<EditText
android:id="#+id/time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="28dp"
android:ems="10"
android:hint="Number of seconds"
android:inputType="numberDecimal" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/time"
android:layout_below="#+id/time"
android:layout_marginRight="60dp"
android:layout_marginTop="120dp"
android:text="Start" />
</RelativeLayout>
my receiver code..
package com.alarmmanager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.util.Log;
import android.widget.Toast;
import java.util.Calendar;
/**
* Created by bhaskar on 24-04-2018.
*
*/
public class MyBroadcastReceiver extends BroadcastReceiver {
MediaPlayer mp;
#Override
public void onReceive(Context context, Intent intent) {
mp= MediaPlayer.create(context, R.raw.alrm );
mp.start();
Toast.makeText(context, "Alarm....", Toast.LENGTH_LONG).show();
Log.i("Alarm","Alarm"+ Calendar.getInstance().getTime());
}
}
mainActivity file
public class MainActivity extends AppCompatActivity {
Button b1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1=(Button) findViewById(R.id.button1);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
startAlert();
}
});
}
public void startAlert() {
EditText text = (EditText) findViewById(R.id.time);
int i = Integer.parseInt(text.getText().toString());
Intent intent = new Intent(this, MyBroadcastReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(
this.getApplicationContext(), 234324243, intent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()
+ (i * 1000), pendingIntent);
Toast.makeText(this, "Alarm set in " + i + " seconds", Toast.LENGTH_LONG).show();
}
}
see this official doc for maintaining alarm when phone gets restarted.
in Start an Alarm When the Device Boots section
After getting the actual code i am editing this answer :
1) create new Receiver instead of using old one receiver
public class SampleBootReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED")) {
// Set the alarm here.
Log.d("AlarmDone", "AlarmDone");
}
}
}
2) register it in manifest file :
<receiver
android:name=".SampleBootReceiver"
android:enabled="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"></action>
</intent-filter>
</receiver>
3) change your old receiver code in menifest :
<receiver android:name=".AlarmReceiver" />
Note : add permission in manifest
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
now your alarm will ring.
For me it works only when i enable auto start
I'm trying to write an battery monitoring application, and one of its function is to keep track of the number of time being recharged and the date associated with it.
First, I wrote everything in the main activity class using SharedPreferences, and it does work. However, I wish to keep track of the number of recharge even in background, so I googled and figured that WakefulBroadcastReceiver + IntentService might be the most efficient/easy way to do it.
I was wrong. I stuck here and I think the problem I'm having right now is that the monitor (the IntentService part) doesn't even start! I think I might have put something wrong in the manifest but I just can't find it.
Here're my codes:
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.mobiledevices.batteryapp" >
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<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=".BootReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
<service
android:name=".RechargeMonitor"
android:exported="false" />
</application>
BootReceiver.java
package com.mobiledevices.batteryapp;
import android.content.Intent;
import android.content.Context;
import android.support.v4.content.WakefulBroadcastReceiver;
public class BootReceiver extends WakefulBroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent){
Intent startServiceIntent = new Intent(context, RechargeMonitor.class);
startWakefulService(context, startServiceIntent);
}
}
RechargeMonitor.java
package com.mobiledevices.batteryapp;
import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.BroadcastReceiver;
import android.content.SharedPreferences;
import android.os.BatteryManager;
import android.widget.Toast;
public class RechargeMonitor extends IntentService {
public RechargeMonitor(){
super("RechargeMonitor");
}
#Override
protected void onHandleIntent(Intent intent){
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
this.registerReceiver(this.batteryinfoReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
}
private BroadcastReceiver batteryinfoReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if(intent.getExtras().getBoolean(BatteryManager.EXTRA_PRESENT) &&
intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0)!=0 &&
intent.getIntExtra(BatteryManager.EXTRA_STATUS, 0)==BatteryManager.BATTERY_STATUS_CHARGING){
SharedPreferences settings = getSharedPreferences(MainActivity.PREF_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
int count = settings.getInt("COUNT", 0);
editor.putInt("COUNT", count+1);
editor.commit();
}
}
};
}
The MainActivity.java is too long so I don't post it here. However, it shouldn't have any problem with that unless I have to call either BootReceiver/RechargeMonitor in the activity file which I guess I don't have to since manifest + BootReciver should be taking care of autostart, and it won't even be a problem.
Again the problem I encounter now is RechargeMonitor doesn't seem to start (I don't see any Toast message.)
Another thing for me to make sure is that SharedPreferences should be accessible everywhere in the same application as long as I have the name right. I've seen that in several places but I need a solid answer.
Thanks!
I am new to android, i am trying a broadcast demo, I gave my best effort by reading the documentation but its not working. Please have a look at my code:
BroadcastDemoActivity.java
package com.broadcastdemo;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
public class BroadcastDemoActivity extends Activity {
/** Called when the activity is first created. */
public static final String PUBLIC_HOLIDAYS = "com.paad.action.PUBLIC_HOLIDAYS";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Intent intent = new Intent(PUBLIC_HOLIDAYS);
intent.putExtra("Holiday", "8th April is a holiday");
sendBroadcast(getIntent());
}
}
Receive.java
package com.broadcastdemo;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
public class Receive extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
String message = intent.getStringExtra("Holiday");
Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
}
}
Manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.broadcastdemo"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="15" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<activity
android:name=".BroadcastDemoActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".Receive">
<intent-filter>
<action android:name="com.paad.action.PUBLIC_HOLIDAYS"/>
</intent-filter>
</receiver>
</application>
</manifest>
I know that i am missing something which i am not aware of, please help.
I believe your problem is in the call to sendBroadcast.
Intent intent = new Intent(PUBLIC_HOLIDAYS);
intent.putExtra("Holiday", "8th April is a holiday");
sendBroadcast(getIntent());
You are not sending the intent that you construct, you're sending the intent returned from getIntent(), which will be the intent that the activity was started with.
It should be
Intent intent = new Intent(PUBLIC_HOLIDAYS);
intent.putExtra("Holiday", "8th April is a holiday");
sendBroadcast(intent);