Android, Why doesn't it pass in my broadcast receiver? - android

I would like to use a broadcastReceiver to catch the headset button click with my android application but it doesn't seem to pass into my receiver class. I looked a large part of questions yet, but no working answers. Thank you.
PS : Sorry for my english ;)
Here's my mainActivity :
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton)findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
IntentFilter filter = new IntentFilter(Intent.ACTION_MEDIA_BUTTON);
HeadsetReceiver r = new HeadsetReceiver();
filter.setPriority(1000);
registerReceiver(r, filter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
My BroadcastReceiver class :
public class HeadsetReceiver extends BroadcastReceiver {
private final String ACTION_BUTTON_HEADSET = "android.intent.action.MEDIA_BUTTON";
#Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals(ACTION_BUTTON_HEADSET)){
System.out.println("Just a test");
}
}
}
And my manifest :
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<receiver class="mypackage.HeadsetReceiver"
android:name="mypackage.HeadsetReceiver">
<intent-filter android:priority="100">
<action android:name="android.intent.action.MEDIA_BUTTON" />
</intent-filter>
</receiver>
<activity
android:name=".MainActivity"
android:label="#string/app_name"
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>

You also have to register your receiver the audio manager. You can do it in your onCreate of your activity:
AudioManager audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
audioManager.registerMediaButtonEventReceiver(
new ComponentName(this, HeadsetReceiver.class));
Also you can delete the IntentFilter code, as it is defined already in your manifest.

Related

How to make an application start on factory reset/first startup?

I am looking to have some basic forms run on my android device after it is reset or on the first boot like most smartphones ask you to connect to Wi-Fi, register the device etc. I haven't worked with native android development previously so what are my options and what areas should I look into?
Try this
BootCompleteReceiver.java
public class BootCompleteReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Intent service = new Intent(context, MsgPushService.class);
context.startService(service);
}
}
MyService.java
public class MyService extends Service {
#Override
public void onCreate() {
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
return Service.START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service Destroy", Toast.LENGTH_LONG).show();
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
}
MainActivity
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
startService(new Intent(getBaseContext(), MyService.class));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
Manifest
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.newbootservice"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="15" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<service android:name=".MyService"/>
<receiver android:name=".BootCompleteReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
<activity
android:name=".MainActivity"
android:label="#string/title_activity_main" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>

Broadcast from app1 to app2

I am trying to broadcast from bc_from to bc_to.
It works fine if I use in Activity bc_to:
registerReceiver(receiver, filter);
It does not work if I define the receiver in the Manifest.
I understand from the docs that since 26 it may be impossible.
So I am looking for any solution that will reach Activity bc_to even if it not running.
Thanks
// package com.yotam17.ori.bc_from;
public class MainActivity extends AppCompatActivity {
private static final String BC_ACTION = "com.yotam17.ori.bc.Broadcast";
private void send() {
Intent intent = new Intent(BC_ACTION);
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
sendBroadcast(intent);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
send();
}
}
And the code for bc_from containes Manifest and two clases:
<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="com.yotam17.ori.bc_to.MyReceiver" >
<intent-filter>
<action android:name="com.yotam17.ori.bc.Broadcast"/>
</intent-filter>
</receiver>
<activity
android:name=".MainActivity"
android:label="#string/app_name"
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>
// package com.yotam17.ori.bc_to;
public class MainActivity extends AppCompatActivity {
private static final String BC_ACTION = "com.yotam17.ori.bc.Broadcast";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Register MyReceiver
IntentFilter filter = new IntentFilter(BC_ACTION);
MyReceiver receiver = new MyReceiver();
registerReceiver(receiver, filter); //<<<<<< Does not work w/o this
}
}
public class MyReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Got it!!!" , Toast.LENGTH_SHORT).show();
}
}
Thanks!
setComponent() solved it.
I never used setComponent() before but found a detailed example here.
To make it a working example - here is the modified send() code:
private void send() {
Intent intent = new Intent(BC_ACTION);
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
intent.setComponent(new ComponentName("com.yotam17.ori.bc_to","com.yotam17.ori.bc_to.MyReceiver"));
sendBroadcast(intent);
}

Pressing a headset button and triggering an event?

I have an earphone, headset. It, vertically, has the buttons, increase volume, middle button, lower volume.
By pressing the middle button, it opens the spotify and plays music, even with the screen off or the phone locked.
I would like to do this for an application of mine, when press this middle button, this application trigger an event, is it possible? Or, press one of the volume buttons and trigger an event.
It is possible? If yes, is there any example, source code, with this application?
EDIT:
The code did not work:
Main:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
IntentFilter filtro = new IntentFilter(Intent.ACTION_MEDIA_BUTTON);//"android.intent.action.MEDIA_BUTTON"
MediaButtonIntentReceiver r = new MediaButtonIntentReceiver();
filtro.setPriority(1000); //this line sets receiver priority
registerReceiver(r, filtro);
}
}
Broadcast:
public class MediaButtonIntentReceiver extends BroadcastReceiver {
public MediaButtonIntentReceiver() {
super();
}
#Override
public void onReceive(Context context, Intent intent) {
String intentAction = intent.getAction();
if (!Intent.ACTION_MEDIA_BUTTON.equals(intentAction)) {
return;
}
KeyEvent event = (KeyEvent) intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
if (event == null) {
return;
}
int action = event.getAction();
if (action == KeyEvent.ACTION_DOWN) {
toDo();
Toast.makeText(context, "BUTTON PRESSED!", Toast.LENGTH_SHORT).show();
}
abortBroadcast();
}
Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.aula.bob.headset">
<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=".MediaButtonIntentReceiver">
<intent-filter>
<action android:name="android.intent.action.MEDIA_BUTTON" />
</intent-filter>
</receiver>
</application>
</manifest>
Create a class extending Broadcast Receiver in your App:
public class MediaButtonIntentReceiver extends BroadcastReceiver {
public MediaButtonIntentReceiver() {
super();
}
#Override
public void onReceive(Context context, Intent intent) {
String intentAction = intent.getAction();
if (!Intent.ACTION_MEDIA_BUTTON.equals(intentAction)) {
return;
}
KeyEvent event = (KeyEvent)intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
if (event == null) {
return;
}
int action = event.getAction();
if (action == KeyEvent.ACTION_DOWN) {
// do something
Toast.makeText(context, "BUTTON PRESSED!", Toast.LENGTH_SHORT).show();
}
abortBroadcast();
}
}
And in your Activity Class:
public class MainActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
IntentFilter filter = new IntentFilter(Intent.ACTION_MEDIA_BUTTON);//"android.intent.action.MEDIA_BUTTON"
MediaButtonIntentReceiver r = new MediaButtonIntentReceiver();
filter.setPriority(10000); //this line sets receiver priority
registerReceiver(r, filter);
}
}
Define your Receiver in Android Manifest like this:
<receiver android:name=".MediaButtonIntentReceiver">
<intent-filter>
<action android:name="android.intent.action.MEDIA_BUTTON" />
</intent-filter>
</receiver>
Hope it will work for you!

unable to send Broadcast from activity to other: android

i have problem with sending Broadcast receive from one activity to other ..its not working my code is below..pls refer to it ..
sending class is:
public class SendBroadcast extends Activity {
public static String BROADCAST_ACTION = "com.unitedcoders.android.broadcasttest.SHOWTOAST";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
sendBroadcast();
}
});
}
public void sendBroadcast(){
Intent broadcast = new Intent();
broadcast.setAction("com.unitedcoders.android.broadcasttest.SHOWTOAST");
sendBroadcast(broadcast);
}
}
and reciving class is :
public class ToastDisplay extends Activity {
private BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Log.i("asdasd","sdasdasd");
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "%%%%%%%%%%%%received", Toast.LENGTH_SHORT).show();
}
};
#Override
protected void onResume() {
IntentFilter filter = new IntentFilter();
filter.addAction(SendBroadcast.BROADCAST_ACTION);
registerReceiver(receiver, filter);
super.onResume();
}
#Override
protected void onPause() {
unregisterReceiver(receiver);
super.onPause();
}
}
Manifest file is ::::
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.unitedcoders.android.broadcasttest"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="4" />
<application android:icon="#drawable/icon" android:label="#string/app_name">
<activity android:name=".SendBroadcast"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".ToastDisplay">
<intent-filter>
<action android:name="com.unitedcoders.android.broadcasttest.SHOWTOAST"> </action>
</intent-filter>
</activity>
</application>
</manifest>
you have not registered your Receiver in Manifest :registered as
<receiver android:name="receiver">
<intent-filter>
<action
android:name="com.unitedcoders.android.broadcasttest.SHOWTOAST"/>
</intent-filter>
</receiver>

Turn off wifi on RINGING phone state

I'm developing an application in which the wifi state goes OFF when the phonestate is RINGING.
My code is as follows :
phonestateManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.phone.state"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="8" />
<application android:icon="#drawable/ic_launcher" >
<activity
android:label="#string/app_name"
android:name=".PhonestateActivity" >
<intent-filter >
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
<action android:name="android.intent.action.PHONE_STATE" />
</intent-filter>
</activity>
<activity android:name=".WifitoggleActivity" />
<receiver android:name=".ServiceReceiver" />
</application>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.UPDATE_DEVICE_STATS" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
</manifest>
PhonestateActivity.java
public class PhonestateActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(PhonestateActivity.this,
ServiceReceiver.class);
startActivity(intent);
}
});
}
}
ServiceReceiver.java
public class ServiceReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
MyPhoneStateListener phoneListener = new MyPhoneStateListener();
TelephonyManager telephony = (TelephonyManager);
context.getSystemService(Context.TELEPHONY_SERVICE);
telephony.listen(phoneListener, MyPhoneStateListener.LISTEN_CALL_STATE);
}
}
MyPhoneStateListener.java
public class MyPhoneStateListener extends PhoneStateListener {
#SuppressWarnings("unused")
private WifitoggleActivity ss;
public void onCallStateChanged(int state, String incomingNumber) {
switch (state) {
case TelephonyManager.CALL_STATE_IDLE:
Log.d("DEBUG", "IDLE");
break;
case TelephonyManager.CALL_STATE_RINGING: {
ss = new WifitoggleActivity();
Log.d("DEBUG", "RINGING");
break;
}
}
}
}
WifitoggleActivity.java
public class WifitoggleActivity extends Activity {
public WifitoggleActivity() {
System.out.print("INSIDE WIFI");
}
/** Called when the activity is first created. */
private WifiManager wifiManager;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.main);
wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
if (wifiManager.isWifiEnabled()) {
wifiManager.setWifiEnabled(false);
} else {
wifiManager.setWifiEnabled(true);
}
}
}
The code is just FORCE CLOSEing in my device. Is it a problem with the Manifest file?
Please help me to find a solution.
Thanks in advance guys.
ServiceReceiver is a BroadcastReceiver not an Activity. You are using wrong code in first block.
Find the onClick handler in your code:
public class PhonestateActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button1= (Button)findViewById(R.id.button1);
button1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Then remove these two lines:
Intent intent = new Intent(PhonestateActivity.this,ServiceReceiver.class);
startActivity(intent);
and replace them by
IntentFilter intentFilter=new IntentFilter(Intent.ACTION_ANSWER);
registerReceiver(new ServiceReceiver(),intentFilter);
As ServiceReceiver is not an activity.
Edited
Add one more permission:
android.permission.PROCESS_OUTGOING_CALLS
and change
<receiver android:name=".ServiceReceiver">
<intent-filter>
<action android:name=" android.intent.action.PHONE_STATE" />
</intent-filter>
</receiver>
Now remove two line that registering broadcast from oncreate method
Check this link

Categories

Resources