How to start app when headset connected to phone in java - java

How could start app or activity when headphone or headset connected to mobile it's possible ? i read some example in another site about broadcast receiver.i'm new in android developing thanks if write example.
private class MusicIntentReceiver extends BroadcastReceiver {
#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:
Toast.makeText(MainActivity.this, "unplug", Toast.LENGTH_SHORT).show();
break;
case 1:
Toast.makeText(MainActivity.this, "plug", Toast.LENGTH_SHORT).show();
break;
default:
}
}
public class MusicIntentReceiver extends WakefulBroadcastReceiver {
public void onReceive(Context ctx, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_HEADSET_PLUG)) {
int state = intent.getIntExtra("state", -1);
switch (state) {
case 0:
Toast.makeText(ctx, "unplug", Toast.LENGTH_SHORT).show();
break;
case 1:
Toast.makeText(ctx, "plug", Toast.LENGTH_SHORT).show();
break;
}
}
}
}
but this code work when application is running.

try this permission to your manifest file.
<receiver
android:name="AudioJackReceiver"
android:enabled="true"
android:exported="true" >
<intent-filter>
<action android:name="android.intent.action.HEADSET_PLUG" />
</intent-filter>
</receiver>

Related

audioManager.startBluetoothSco() is not working on android

I'm setting up AudioManager with bluetooth to record an audio , the code is already there but not working and whenever i check for AudioManager.EXTRA_SCO_AUDIO_STATE , it never connects and returns -1 , i do not know why , can anyone please guide me to solve this issue , Thank you .
This is my receiver
public class CallReceiver extends BroadcastReceiver {
public CallReceiver() {
super();
}
#Override
public void onReceive(Context context, Intent intent) {
Bundle bundle;
String state;
String incomingNumber;
String action = intent.getAction();
int BLE = intent.getIntExtra(AudioManager.EXTRA_SCO_AUDIO_STATE, -1); // always return -1
if (BLE == AudioManager.SCO_AUDIO_STATE_CONNECTED){ // never connected
// start bluetooth headset
AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE)
audioManager.setMode(AudioManager.MODE_IN_CALL);
audioManager.setBluetoothScoOn(true);
audioManager.startBluetoothSco();
}
}
}
Receiver in Manifest File
<receiver
android:name=".recorder.CallReceiver"
android:exported="true">
<intent-filter>
<action android:name="android.media.extra.SCO_AUDIO_STATE"/>
<action
android:name="android.media.ACTION_SCO_AUDIO_STATE_UPDATED"/>
</intent-filter>
</receiver>
Before checking the current state, first need to find the action, I check for AudioManager.EXTRA_SCO_AUDIO_STATE, it never connects and returns -1. After finding the current state, If found 'SCO_AUDIO_STATE_CONNECTED' setBluetoothScoOn and startBluetoothSco.
#Override public void onReceive(Context context, Intent intent)
{
String action = intent.getAction();
if (action.equalsIgnoreCase(AudioManager.ACTION_SCO_AUDIO_STATE_UPDATED))
{
int currentState = context . getIntExtra (AudioManager.EXTRA_SCO_AUDIO_STATE, -1);
Log.d("Bluetooth Connect - ", "Audio SCO: " + AudioManager.ACTION_SCO_AUDIO_STATE_UPDATED);
switch(currentState) {
case AudioManager.SCO_AUDIO_STATE_CONNECTED :
{
Log.i("Bluetooth Connect", "SCO_AUDIO_STATE_CONNECTED");
AudioManager audioManager =(AudioManager) context . getSystemService (Context.AUDIO_SERVICE)
audioManager.setMode(AudioManager.MODE_IN_CALL);
audioManager.setBluetoothScoOn(true);
audioManager.startBluetoothSco();
}
break;
case AudioManager.SCO_AUDIO_STATE_DISCONNECTED :
{
Log.e("Bluetooth disconnect", "SCO_AUDIO_STATE_DISCONNECTED");
}
break;
default: Log.e("Bluetooth unknown - ", "unknown state received:"+l_state);
}
} else Log.e("Bluetooth Connect - ", "onReceive:action=" + action);
}

how to unlock phone from service [duplicate]

I am doing an application which Locks the screen on shake. Now it is locking and from there it going to a broadcast receiver from there if the screen is off its entering into a service which has to turn the screen on.
Below is the broadcast receiver:
public class ScreenReceiver extends BroadcastReceiver {
public static boolean wasScreenOn = true;
#Override
public void onReceive(Context context, Intent intent) {
System.out.println("Entered Broadcaste Reciever");
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
// DO WHATEVER YOU NEED TO DO HERE
System.out.println("SCREEN_OFF"+wasScreenOn);
wasScreenOn = false;
Intent i = new Intent(context, UpdateService.class);
i.putExtra("screen_state", wasScreenOn);
context.startService(i);
System.out.println("jrkejhr keh");
}
else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
// AND DO WHATEVER YOU NEED TO DO HERE
wasScreenOn = true;
System.out.println("SCREEN_ON"+wasScreenOn);
}
}
And its entering to a service where i had written the intent action to go home is...
ShakeListener mShaker;
int amountOfTime = 0;
Context context1;
#Override
public void onCreate() {
super.onCreate();
// REGISTER RECEIVER THAT HANDLES SCREEN ON AND SCREEN OFF LOGIC
System.out.println("Enterd Service");
final Vibrator vibe = (Vibrator)getSystemService(Context.VIBRATOR_SERVICE);
mShaker = new ShakeListener(this);
mShaker.setOnShakeListener(new ShakeListener.OnShakeListener () {
public void onShake() {
vibe.vibrate(100);
Intent goHome = new Intent();
goHome.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
goHome.setAction("android.intent.action.MAIN");
goHome.addCategory("android.intent.category.HOME");
startActivity(goHome);
}
});
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
It is entering into the service. But home screen is not displaying. When the service is invoked the the screen is locked.
Edit:
As some folks needs help in Unlocking device after locking programmatically,
I came through post Android screen lock/ unlock programatically, please have look, may help you.
Original Answer was:
You need to get Admin permission and you can lock phone screen
please check below simple tutorial to achive this one
Lock Phone Screen Programmtically
also here is the code example..
LockScreenActivity.java
public class LockScreenActivity extends Activity implements OnClickListener {
private Button lock;
private Button disable;
private Button enable;
static final int RESULT_ENABLE = 1;
DevicePolicyManager deviceManger;
ActivityManager activityManager;
ComponentName compName;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
deviceManger = (DevicePolicyManager)getSystemService(
Context.DEVICE_POLICY_SERVICE);
activityManager = (ActivityManager)getSystemService(
Context.ACTIVITY_SERVICE);
compName = new ComponentName(this, MyAdmin.class);
setContentView(R.layout.main);
lock =(Button)findViewById(R.id.lock);
lock.setOnClickListener(this);
disable = (Button)findViewById(R.id.btnDisable);
enable =(Button)findViewById(R.id.btnEnable);
disable.setOnClickListener(this);
enable.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if(v == lock){
boolean active = deviceManger.isAdminActive(compName);
if (active) {
deviceManger.lockNow();
}
}
if(v == enable){
Intent intent = new Intent(DevicePolicyManager
.ACTION_ADD_DEVICE_ADMIN);
intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN,
compName);
intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION,
"Additional text explaining why this needs to be added.");
startActivityForResult(intent, RESULT_ENABLE);
}
if(v == disable){
deviceManger.removeActiveAdmin(compName);
updateButtonStates();
}
}
private void updateButtonStates() {
boolean active = deviceManger.isAdminActive(compName);
if (active) {
enable.setEnabled(false);
disable.setEnabled(true);
} else {
enable.setEnabled(true);
disable.setEnabled(false);
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case RESULT_ENABLE:
if (resultCode == Activity.RESULT_OK) {
Log.i("DeviceAdminSample", "Admin enabled!");
} else {
Log.i("DeviceAdminSample", "Admin enable FAILED!");
}
return;
}
super.onActivityResult(requestCode, resultCode, data);
}
}
MyAdmin.java
public class MyAdmin extends DeviceAdminReceiver{
static SharedPreferences getSamplePreferences(Context context) {
return context.getSharedPreferences(
DeviceAdminReceiver.class.getName(), 0);
}
static String PREF_PASSWORD_QUALITY = "password_quality";
static String PREF_PASSWORD_LENGTH = "password_length";
static String PREF_MAX_FAILED_PW = "max_failed_pw";
void showToast(Context context, CharSequence msg) {
Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
}
#Override
public void onEnabled(Context context, Intent intent) {
showToast(context, "Sample Device Admin: enabled");
}
#Override
public CharSequence onDisableRequested(Context context, Intent intent) {
return "This is an optional message to warn the user about disabling.";
}
#Override
public void onDisabled(Context context, Intent intent) {
showToast(context, "Sample Device Admin: disabled");
}
#Override
public void onPasswordChanged(Context context, Intent intent) {
showToast(context, "Sample Device Admin: pw changed");
}
#Override
public void onPasswordFailed(Context context, Intent intent) {
showToast(context, "Sample Device Admin: pw failed");
}
#Override
public void onPasswordSucceeded(Context context, Intent intent) {
showToast(context, "Sample Device Admin: pw succeeded");
}
}
The androidmanifest.xml and policies.xml files on the sample page are invisible in my browser due to it trying to format the XML files as HTML. I'm only posting this for reference for the convenience of others, this is sourced from the sample page.
Thanks all for this helpful question!
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.kns"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="8" />
<application android:icon="#drawable/icon" android:label="#string/app_name">
<activity android:name=".LockScreenActivity"
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=".MyAdmin"
android:permission="android.permission.BIND_DEVICE_ADMIN">
<meta-data android:name="android.app.device_admin"
android:resource="#xml/policies" />
<intent-filter>
<action android:name="android.app.action.DEVICE_ADMIN_ENABLED" />
</intent-filter>
</receiver>
</application>
</manifest>
policies.xml
<?xml version="1.0" encoding="utf-8"?>
<device-admin xmlns:android="http://schemas.android.com/apk/res/android">
<uses-policies>
<limit-password />
<watch-login />
<reset-password />
<force-lock />
<wipe-data />
</uses-policies>
</device-admin>
Use Activity.getWindow() to get the window of your activity; use Window.addFlags() to add whichever of the following flags in WindowManager.LayoutParams that you desire:
FLAG_DISMISS_KEYGUARD
FLAG_SHOW_WHEN_LOCKED
FLAG_TURN_SCREEN_ON

Android Broadcast receiver for call not working? (Marshmallow)

I am trying to display toast after receiving an call, I have implemented all necessary things needed to register broadcast receiver but it is not displaying toast. I am trying to run this program on Marshmallow device
MyCallReceiver.java -
package com.suhas.callreceiver;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.Toast;
public class MyCallReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(TelephonyManager.EXTRA_STATE_RINGING)) {
// This code will execute when the phone has an incoming call
// get the phone number
String incomingNumber = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);
Toast.makeText(context, "Call from:" +incomingNumber, Toast.LENGTH_LONG).show();
Log.d("MyTrack call", "call receive");
} else if (intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(
TelephonyManager.EXTRA_STATE_IDLE))
{
Toast.makeText(context, "Detected call hangup event", Toast.LENGTH_LONG).show();
}
else if (intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(
TelephonyManager.EXTRA_STATE_OFFHOOK)) {
// This code will execute when the call is disconnected
}
}
}
AndroidManifest.xml -
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.suhas.msgmanager">
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
<application
android:allowBackup="true"
android:icon="#mipmap/msgis"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<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>
<activity android:name="com.example.suhas.msgmanager.MyDialog" android:launchMode="singleTask"
android:theme="#android:style/Theme.Translucent" />
<service android:name="com.example.suhas.msgmanager.ChatHeadService"></service>
<receiver android:name=".MyCallReceiver">
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE" />
</intent-filter>
</receiver>
<activity android:name=".AddMessageActivity">
</activity>
</application>
</manifest>
I have one MainActivity with one default label saying Hello World.
In Case of Marshmallow Version, We have a concept called Runtime permission which is to be made inside Activity in order to work with the permission.
Runtime permission provides a way to ask user for particular permission at runtime while he runs activity for first time.
This are two things you have to specify :
//specify any constant number for permission
public final static int MY_PERMISSIONS_REQUEST_READ_PHONE_STATE = 11;
// Specify following bit of code in OnCreate method
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Here, thisActivity is the current activity
if (ContextCompat.checkSelfPermission(getApplicationContext(),
Manifest.permission.READ_PHONE_STATE)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.READ_CONTACTS)) {
} else {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.READ_PHONE_STATE},
MY_PERMISSIONS_REQUEST_READ_PHONE_STATE);
}
}
}
//specify this method which will popup window asking user for permission at runtime
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_READ_PHONE_STATE: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
} else {
}
return;
}
}
}
this will provide a way to work with Marshmallow devices
You have given wrong package name in the receiver.
You should define receiver as below:
<receiver android:name="com.suhas.callreceiver.MyCallReceiver">
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE" />
</intent-filter>
</receiver>
In target API 23 or higher as per the Marshmallow the applications needs run time permission or manual in your device setting>> apps>> select your app>> permission
this link can help you
I successfully implemented in our App. Get the reference from here.
Call Receive Method
public class CallReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
//Log.w("intent " , intent.getAction().toString());
TelephonyManager telephony = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
MyPhoneStateListener customPhoneListener = new MyPhoneStateListener();
telephony.listen(customPhoneListener, PhoneStateListener.LISTEN_CALL_STATE);
Bundle bundle = intent.getExtras();
String phone_number = bundle.getString("incoming_number");
String stateStr = intent.getExtras().getString(TelephonyManager.EXTRA_STATE);
// String number = intent.getExtras().getString(TelephonyManager.EXTRA_INCOMING_NUMBER);
int state = 0;
if(stateStr.equals(TelephonyManager.EXTRA_STATE_IDLE)){
state = TelephonyManager.CALL_STATE_IDLE;
}
else if(stateStr.equals(TelephonyManager.EXTRA_STATE_OFFHOOK)){
state = TelephonyManager.CALL_STATE_OFFHOOK;
}
else if(stateStr.equals(TelephonyManager.EXTRA_STATE_RINGING)){
state = TelephonyManager.CALL_STATE_RINGING;
}
if (phone_number == null || "".equals(phone_number)) {
return;
}
customPhoneListener.onCallStateChanged(context, state, phone_number);
Toast.makeText(context, "Phone Number " + phone_number , Toast.LENGTH_SHORT).show();
}}
Listener Method
public class MyPhoneStateListener extends PhoneStateListener {
private static int lastState = TelephonyManager.CALL_STATE_IDLE;
private static Date callStartTime;
private static boolean isIncoming;
public void onCallStateChanged(Context context, int state, String phoneNumber){
if(lastState == state){
//No change, debounce extras
return;
}
System.out.println("Number inside onCallStateChange : " + phoneNumber);
switch(state){
case TelephonyManager.CALL_STATE_RINGING:
isIncoming = true;
callStartTime = new Date();
Toast.makeText(context, "Incoming Call Ringing " + phoneNumber, Toast.LENGTH_SHORT).show();
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
if(lastState != TelephonyManager.CALL_STATE_RINGING){
isIncoming = false;
callStartTime = new Date();
Toast.makeText(context, "Outgoing Call Started " + phoneNumber, Toast.LENGTH_SHORT).show();
}
break;
case TelephonyManager.CALL_STATE_IDLE:
//Went to idle- this is the end of a call. What type depends on previous state(s)
if(lastState == TelephonyManager.CALL_STATE_RINGING){
//Ring but no pickup- a miss
Toast.makeText(context, "Ringing but no pickup" + phoneNumber + " Call time " + callStartTime +" Date " + new Date() , Toast.LENGTH_SHORT).show();
}
else if(isIncoming){
Toast.makeText(context, "Incoming " + phoneNumber + " Call time " + callStartTime , Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(context, "outgoing " + phoneNumber + " Call time " + callStartTime +" Date " + new Date() , Toast.LENGTH_SHORT).show();
}
break;
}
lastState = state;
}} }
Get the reference for full solution

Listening for phone code not executing?

My app plays audio, and so I want to mute my app's audio when the user gets a call. That way the music won't be playing over the users call. I have used phoneStateListener , but for some reason the methods in it aren't executing-I know because the logs aren't displaying:
PhoneStateListener phoneStateListener = new PhoneStateListener() {
#Override
public void onCallStateChanged(int state, String incomingNumber) {
if (state == TelephonyManager.CALL_STATE_RINGING) {
//Incoming call: Pause music
TwentySeconds.stopTimer(); //Stop service which mutes app
Intent i = new Intent(BaseActivity.this, Main_Menu.class);
startActivity(i);
Toast.makeText(BaseActivity.this, "INCOMING CALL", Toast.LENGTH_SHORT).show();
Log.v(TAG, "INCOMING CALL");
} else if (state == TelephonyManager.CALL_STATE_IDLE) {
//Not in call: Play music
Log.v(TAG, "NOT IN A CALL");
} else if (state == TelephonyManager.CALL_STATE_OFFHOOK) {
//A call is dialing, active or on hold
TwentySeconds.stopTimer(); //Stop service which mutes app
Intent i = new Intent(BaseActivity.this, Main_Menu.class);
startActivity(i);
Log.v(TAG, "CALL IS ACTIVE!");
Toast.makeText(BaseActivity.this, "DIALING", Toast.LENGTH_SHORT).show();
}
}
};
I have looked all over the web to find out how to do this--One way is I found is to use the intent, but that requires extending BroadcastReceiver, and I can't extend two things. So, for now, the phoneStateListener is doing absolutely nothing. I really appreciate all of your help in fixing my PhoneStateListener.
Thanks,
Rich
Did you forget to quote the TelephonyManager?
TelephonyManager manager = this.getSystemService(TELEPHONY_SERVICE);
Try this:
public class PhoneCallStateActivity extends Activity {
TelephonyManager manager;
#override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
manager = (TelephonyManager) this.getSystemService(TELEPHONY_SERVICE);
manager.listen(new MyPhoneStateListener(), PhoneStateListener.LISTEN_CALL_STATE);
}
class MyPhoneStateListener extends PhoneStateListener{
#override
public void onCallStateChanged(int state, String incomingNumber) {
switch(state) {
case TelephonyManager.CALL_STATE_IDLE:
//TODO:
break;
case TelephonyManager.CALL_STATE_RINGING:
//TODO:
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
//TODO:
break;
default:
break;
}
}
super.onCallStateChanged(state, incomingNumber);
}
}
I looked at your code,it is good. But i am just thinking about your manifest file, did you given enough permissions to read phone state. Have a look at my manifest file (which is working):
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.truiton.phonestatelistener"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="21" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".PhoneStateListenerActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
It is better to access / use this "Custom Phone State Listener" class with the TelephonyManager like as follows:
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
public class PhoneStateListenerActivity extends ActionBarActivity {
TelephonyManager tManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
tManager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
tManager.listen(new CustomPhoneStateListener(this),
PhoneStateListener.LISTEN_CALL_STATE
| PhoneStateListener.LISTEN_CELL_INFO // Requires API 17
| PhoneStateListener.LISTEN_CELL_LOCATION
| PhoneStateListener.LISTEN_DATA_ACTIVITY
| PhoneStateListener.LISTEN_DATA_CONNECTION_STATE
| PhoneStateListener.LISTEN_SERVICE_STATE
| PhoneStateListener.LISTEN_SIGNAL_STRENGTHS
| PhoneStateListener.LISTEN_CALL_FORWARDING_INDICATOR
| PhoneStateListener.LISTEN_MESSAGE_WAITING_INDICATOR);
}
}
Here we are setting the tManager.listen method a new object for CustomPhoneStateListener and in the events parameter a bitwise-OR combination of Android PhoneStateListener LISTEN_ flags is passed.
You can set your own custom phone state listener, (I am just adding mine here) :
public class CustomPhoneStateListener extends PhoneStateListener {
public CustomPhoneStateListener(Context context) {
mContext = context;
}
#Override
public void onCallStateChanged(int state, String incomingNumber) {
super.onCallStateChanged(state, incomingNumber);
switch (state) {
case TelephonyManager.CALL_STATE_IDLE:
Log.i(LOG_TAG, "onCallStateChanged: CALL_STATE_IDLE");
break;
case TelephonyManager.CALL_STATE_RINGING:
Log.i(LOG_TAG, "onCallStateChanged: CALL_STATE_RINGING");
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
Log.i(LOG_TAG, "onCallStateChanged: CALL_STATE_OFFHOOK");
break;
default:
Log.i(LOG_TAG, "UNKNOWN_STATE: " + state);
break;
}
}

Simple service won't bind : bindService return false, service connection never triggered

This is my first time using Service in Android and my service won't bind.
The Service code :
package mackosoft.almightymessage;
public final class MainService extends Service {
private final static String TAG = "Main Service";
private final IBinder binder = new MainServiceBinder();
#Override
public final void onCreate() {
super.onCreate();
Log.d(TAG, "Service created");
Toast.makeText(this, "Service created", Toast.LENGTH_SHORT).show();
}
#Override
public final int onStartCommand(final Intent intent, final int flags, final int startId) {
return START_STICKY;
}
#Override
public final void onDestroy() {
super.onDestroy();
Log.d(TAG, "Service created");
Toast.makeText(this, "Service destroyed", Toast.LENGTH_SHORT).show();
}
#Override
public final IBinder onBind(final Intent intent) {
Toast.makeText(this, "Service binded", Toast.LENGTH_SHORT).show();
return this.binder;
}
public final class MainServiceBinder extends Binder {
final MainService getService() {
return MainService.this;
}
}
}
Manifest file :
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="mackosoft.almightymessage" >
<application
android:allowBackup="true"
android:icon="#drawable/ic_logo"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:configChanges="orientation|keyboardHidden"
android:icon="#drawable/ic_logo"
android:label="#string/app_name"
android:screenOrientation="portrait" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".MainService"
android:enabled="true" >
</service>
</Application
</manifest>
And finally the part in MainActivity where I try to bind the service :
public final class MainActivity extends AppCompatActivity {
#Override
protected final void onStart() {
super.onStart();
final Intent intent = new Intent(MainActivity.this, MainService.MainServiceBinder.class);
final boolean status = bindService(intent, this.connection, Context.BIND_AUTO_CREATE);
Log.d(TAG, "Service binded ? " + status);
}
private final ServiceConnection connection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
Log.d(TAG, "Service connected !");
service = ((MainService.MainServiceBinder) iBinder).getService(); // service is a private member of MainActivity
}
#Override
public void onServiceDisconnected(ComponentName componentName) {
Log.d(TAG, "Service disconnected !");
}
};
}
Running the application, Logcat shows :
mackosoft.almightymessage D/MainActivity﹕ Service binded ? false
And Service Connection is NEVER triggered !
I tried multiple solution :
Moving the binding call to a Button.onClick() and using getApplicationContext()
Using directly getApplicationContext()
In the Manifest, changed -> android:name="mackosoft.almightymessage.MainService"
Changed also the Intent-> final Intent intent = new Intent(this, MainService.MainServiceBinder.class);
Also tried to add this.startService(intent) and with this.getApplicationContext()
All of the above fail and no error in the logs !
I have no luck at all.
Test device : Samsung Galaxy Note 3 running Cyanogen Mode 12.1 (Android 5.1)
Android Studio 1.2.1.1 (stable)
Thanks for the help !!
final Intent intent = new Intent(MainActivity.this, MainService.MainServiceBinder.class);
Should be
final Intent intent = new Intent(MainActivity.this, MainService.class);
See the example provided in the docs for further info

Categories