Android Broadcast Receiver not working (with two receiver) - java

I have two BroadcastReceiver and only one is working now.
Manifest
<receiver
android:name="com.example.basicplayerapp.core.AudioJackReceiver"
android:enabled="true"
android:exported="true" >
<intent-filter>
<action android:name="android.intent.action.HEADSET_PLUG" />
</intent-filter>
</receiver>
<!-- WebSocket -->
<receiver
android:name="com.example.basicplayerapp.core.NetworkReceiver">
<intent-filter >
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
<service android:name="com.example.basicplayerapp.core.WebSocketServices"></service>
When I have only the AudioJackReceiver it works prefect. Now that I added NetworkReceiver the AudioJackReceiver stopped work. Any advice please. thanks.
onCreate of the Video Activity
if (HEADSET_ONLY) { myAudioJackReceiver = new AudioJackReceiver(); }
AudioJackReceiver
public class AudioJackReceiver extends BroadcastReceiver {
public static final String TAG = AudioJackReceiver.class.getSimpleName();
#Override
public void onReceive(Context context, Intent intent) {
AudioManager audio = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
if (intent.getAction().equals(Intent.ACTION_HEADSET_PLUG)) {
int state = intent.getIntExtra("state", -1);
switch (state) {
case 0:
audio.setStreamMute(AudioManager.STREAM_MUSIC, true);
Toast.makeText(context, "Please plug in your headset to enjoy the sound.", Toast.LENGTH_LONG).show();
makeLog("i", "Headset is unplugged");
break;
case 1:
audio.setStreamMute(AudioManager.STREAM_MUSIC, false);
makeLog("i", "Headset is plugged");
break;
default:
makeLog("i", "I have no idea what the headset state is");
Toast.makeText(context, "ERROR => I have no idea what the headset state is", Toast.LENGTH_LONG).show();
}
}
}//end onReceive
NetworkReceiver
public class NetworkReceiver extends BroadcastReceiver {
public static final String TAG = NetworkReceiver.class.getSimpleName();
#Override
public void onReceive(Context context, Intent intent) {
Log.i(TAG, "onReceive");
ConnectivityManager conn = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = conn.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.getDetailedState() == NetworkInfo.DetailedState.CONNECTED) {
Log.i(TAG, "connected");
Intent startServiceIntent = new Intent(context, WebSocketServices.class);
context.startService(startServiceIntent);
}
else if(networkInfo != null){
NetworkInfo.DetailedState state = networkInfo.getDetailedState();
Log.i(TAG, state.name());
}
else {
Log.i(TAG, "lost connection");
}
}//end onReceive
};//end NetworkReceiver

Related

How can I display the incoming number as a Toast?

I have to make a simple App for school.
It has to show a toast when a call is received.
The phone call receiver doesn't display anything.
I have this in my manifest, so permissions shouldn't be the issue
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<receiver
android:name=".ReceptorLlamadas"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE"/>
</intent-filter>
</receiver>
The code for my broadcastReceiver
public class ReceptorLlamadas extends BroadcastReceiver {
Context context;
#Override
public void onReceive(Context c, Intent intent) {
try {
TelephonyManager manager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
LlamadaListener listener = new LlamadaListener();
manager.listen(listener, PhoneStateListener.LISTEN_CALL_STATE);
} catch (Exception e) {
Log.e("PhoneCallError", "onReceive: ", e);
}
}
private class LlamadaListener extends PhoneStateListener {
public void onCallStateChanged(int state, String phoneNumber) {
if (state == 1) {
String mensaje = "Llamada entrante del número: " + phoneNumber;
int duracion = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, mensaje, duracion);
toast.show();
}
}
}
}
Sorry if I messed up the formatting
Edit: forgot to include some code
You need to declare Broadcast Receiver in Android Manifest as well just like this in Application tag:
<receiver
android:name=".ReceptorLlamadas"
android:enabled="true" />

Don't work intent action in received

I have some problem with intent action in broadcast receiver, when alarm is ringing in log action ALARM_ALERT output, but when i off alarm on my phone Huawei Honor 5A, i don't see action in log ALARM_DONE.
Notice: I test this code on Genymotion on Android, this work fine, but on my phone install MUI, maybe it's problem?
public class BootReceiver extends BroadcastReceiver {
private static final String TAG = "LockScreen/BootReceiver";
#SuppressLint("WrongConstant")
#Override
public void onReceive(final Context context, Intent intent) {
String action = intent.getAction();
Log.e(TAG,"onReceive " + action);
//If the screen was just turned on or it just booted up, start your Lock Activity
if (action.equals("com.android.deskclock.ALARM_ALERT") ||
action.equals("com.android.deskclock.ALARM_SNOOZE"))
{
UserHolder.setRingState(true);
}
if(action.equals("com.android.deskclock.ALARM_DISMISS") ||
action.equals("com.android.deskclock.ALARM_DONE")) {
UserHolder.setRingState(false);
}
if (action.equals(Intent.ACTION_SCREEN_OFF)
|| action.equals(Intent.ACTION_SCREEN_ON)
|| action.equals(Intent.ACTION_BOOT_COMPLETED)) {
if (action.equals(Intent.ACTION_SCREEN_OFF)) {
//LockScreenService.service.stopForeground(true);
UserHolder.saveScreenOff(context);
}
Parameters parameters = Parameters.getFromDB();
if (!UserHolder.isAlarm() &&!UserHolder.callIsRunning()
&& UserHolder.isLogin() && parameters.getUserWidgetOnoff() == 1) {
Intent i = new Intent(context, LockScreenActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//i.addFlags(WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY);
context.startActivity(i);
} else {
Logger.info("ignore onReceive " + action);
}
}
Intent filter:
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
filter.addAction(Intent.ACTION_BOOT_COMPLETED);
filter.addAction("com.android.deskclock.ALARM_ALERT");
filter.addAction("com.android.deskclock.ALARM_SNOOZE");
filter.addAction("com.android.deskclock.ALARM_DISMISS");
filter.addAction("com.android.deskclock.ALARM_DONE");
Manifest:
<receiver
android:name=".receiver.BootReceiver"
android:enabled="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="com.android.deskclock.ALARM_ALERT" />
<action android:name="com.android.deskclock.ALARM_SNOOZE" />
<action android:name="com.android.deskclock.ALARM_DISMISS" />
<action android:name="com.android.deskclock.ALARM_DONE" />
</intent-filter>
</receiver>

Android - Start App Upon Phone Call

Is there any way to develop an app that starts up when a user receives a phone call? I can't really go into details about the idea but was wondering if there was some call that would allow that to happen.
You can use a Broadcast Receiver for thatlike this
public class PhoneStatReceiver extends BroadcastReceiver{
private static final String TAG = "PhoneStatReceiver";
private static boolean incomingFlag = false;
private static String incoming_number = null;
#Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals(Intent.ACTION_NEW_OUTGOING_CALL)){
incomingFlag = false;
String phoneNumber = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
Log.i(TAG, "call OUT:"+phoneNumber);
}else{
TelephonyManager tm = (TelephonyManager)context.getSystemService(Service.TELEPHONY_SERVICE);
switch (tm.getCallState()) {
case TelephonyManager.CALL_STATE_RINGING:
incomingFlag = true;//标识当前是来电
incoming_number = intent.getStringExtra("incoming_number");
Log.i(TAG, "RINGING :"+ incoming_number);
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
if(incomingFlag){
Log.i(TAG, "incoming ACCEPT :"+ incoming_number);
}
break;
case TelephonyManager.CALL_STATE_IDLE:
if(incomingFlag){
Log.i(TAG, "incoming IDLE");
}
break;
}
}
}
}
Register this receiver in AndroidManifest like this
<receiver android:name=".filter.PhoneStatReceiver">
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE"/>
<action android:name="android.intent.action.NEW_OUTGOING_CALL" />
</intent-filter>
</receiver>
<uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>
<uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS"></uses-permission>
Yes We can start an diffrent app when User receives a phone call.Example :- Truecaller,Mobile no. Tracker apps.
You can use Services for this.
public class CallReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
final Context cont = context;
final Intent in = intent;
if (state.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent i = new Intent(cont, MainActivity.class);
i.putExtras(in);
i.addCategory(Intent.CATEGORY_LAUNCHER);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
cont.startActivity(i);
}
}, 1000);
}
}
}
You must implement this handler with postDelayed so that your activity screen can be on top of native call screen. If you dont want this to happen then you must remove this handler.
Add these to your manifest--
<receiver
android:name=".CallReceiver"
android:enabled="true" >
<intent-filter android:priority="1000" >
<action android:name="android.intent.action.PHONE_STATE" />
</intent-filter>
</receiver>
and
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.PROCESS_INCOMING_CALLS" />
You have to use another extra_state for onreceiving call. This is for ringing state.

Query a web page

How must I go about coding to get an app to query the state of a device, through internet protocol to see if its on or off.
public void port0156 (View view) {
webView = (WebView) findViewById(R.id.webView);
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("http://192.168.2.66/index.html?o0=1");
}
You can register a broadcastreceiver to monitor connectivity changes.
In manifest :
<receiver android:name="com.yourpackage.NetworkChangeReciever" >
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
the class in com.yourpackage :
public class NetworkChangeReciever extends BroadcastReceiver {
private final static String TAG = "NetworkChangeReciever";
public interface NetworkChangeRecieverListener {
public void OnNetworkChangeReciever(boolean wifiConnected);
}
#Override
public void onReceive(final Context context, final Intent intent) {
final ConnectivityManager connMgr = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
final android.net.NetworkInfo wifi = connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
final android.net.NetworkInfo mobile = connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if (wifi.isAvailable()) || mobile.isAvailable()) {
Log.d(TAG, "Network Available.");
}
else {
Log.d(TAG, "Network Unavailable");
}
}
}
You can see if the app is online (or reachable) by seeing if it returns a ping you can easily do this by using OS and parsing the output.

how to stop displaying apps in active application window in android

I made an app as a service which runs in background. This app is basically a battery alarm. It works fine but the only problem is that when this service is running it also displays this app in the active application task manager. So when I exit this app it stops that service as well. So what I want is to only stop this service when the user unchecks the box in the app settings. If it is checked then it should not be stopped even if it is closed in active application task manager.
How can I stop showing my app in task manager?
I think I should provide code over here This is my service class
public class BatteryService extends Service {
Notify notification = new Notify();
BatteryAlarm alarm = new BatteryAlarm();
private MediaPlayer mMediaPlayer;
boolean flag = false;
#Override
public IBinder onBind(Intent arg0) {
return null;
}
//method to start service
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
notification.initNotification(this, false);
this.registerReceiver(this.mBatInfoReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
return START_STICKY;
}
//Broadcast receiver to get battery info
private BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver(){
#Override
public void onReceive(Context c, Intent i) {
//notification.initNotification(c);
int level = i.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
int plugged = i.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0);
SharedPreferences getAlarm = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
String alarms = getAlarm.getString("ringtones", "content://media/internal/audio/media/45"); // /system/media/audio/ringtones/ANDROMEDA.ogg , content://media/internal/audio/media/45
Uri uri = Uri.parse(alarms);
if(plugged == 2) {
if(level == 100) {
if(uri != null) {
if(flag == false) {
playAlarm(c, uri);
notification.initNotification(c, true);
Toast.makeText(c, "Battery charge is completed. Unplug your mobile phone!", Toast.LENGTH_LONG).show();
flag = true;
}
}
}
} else if (plugged == 0) {
if(uri != null) {
stopAlarm();
}
notification.cancelNotification(c);
//Toast.makeText(c, "Mobile is unplugged", Toast.LENGTH_LONG).show();
}
}
};
//play alarm method
private void playAlarm(Context c, Uri uri) {
mMediaPlayer = new MediaPlayer();
try {
mMediaPlayer.reset();
mMediaPlayer.setDataSource(getBaseContext(), uri);
final AudioManager audioManager = (AudioManager) c.getSystemService(Context.AUDIO_SERVICE);
if (audioManager.getStreamVolume(AudioManager.STREAM_ALARM) != 0) {
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
mMediaPlayer.prepare();
mMediaPlayer.start();
}
} catch (Exception ex) {
ex.printStackTrace();
onDestroy();
}
}
//method to stop playing alarm
private void stopAlarm() {
mMediaPlayer.stop();
flag = false;
}
//method to stop service
public void onDestroy() {
super.onDestroy();
notification.cancelNotification(this);
unregisterReceiver(this.mBatInfoReceiver);
stopAlarm();
Toast.makeText(this, "Service Stopped", Toast.LENGTH_LONG).show();
}
}
This is my main activity
public class BatteryNotify extends PreferenceActivity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.xml.prefs);
addPreferencesFromResource(R.xml.prefs);
SharedPreferences getCB = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
boolean cb = getCB.getBoolean("checkbox", true);
final CheckBoxPreference checkboxPref = (CheckBoxPreference) getPreferenceManager().findPreference("checkbox");
if(cb == true) {
startService(new Intent(getBaseContext(), BatteryService.class));
} else if(cb == false) {
stopService(new Intent(getBaseContext(), BatteryService.class));
}
checkboxPref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
public boolean onPreferenceChange(Preference preference, Object newValue) {
if(newValue.toString().equals("true")) {
startService(new Intent(getBaseContext(), BatteryService.class));
} else {
stopService(new Intent(getBaseContext(), BatteryService.class));
}
return true;
}
});
}
}
and here is my menifest file
<uses-sdk android:minSdkVersion="10" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<activity
android:name=".BatteryNotify"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".BatteryService"></service>
</application>
The best way to do this would be to create a BroadcastReceiver, register it in the manifest with the appropriate intent-filters and when it receives one it starts the Service or Activity to perform whatever task you need.
EDIT:
Create your BroadcastReceiver as a separate class and register it in the manifest. When it receives a battery event, create a PendingIntent to start the Service. That way it doesn't matter if your app isn't running. It will be started for you.
How can I stop showing my app in task manager?
You can't, for obvious security reasons.

Categories

Resources