- Forum-Beiträge: 1
15.11.2016, 19:59:19 via Website
15.11.2016 19:59:19 via Website
Hi guys
I have been trying to make a simple global broadcast for the phone state; but I keep getting null back and it only seems to run once at start of program. Any ideas and specifically example of how to correct this? ideally each time the phone state changes I want to get the information from my reciever.
here is my MainActivity
package com.example.hdm.globalreciever;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.telephony.TelephonyManager;
public class MainActivity extends Activity {
MyReceiver receiver;
IntentFilter filter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
IntentFilter filter = new IntentFilter("com.pycitup.BroadcastReceiver");
filter.addAction(TelephonyManager.ACTION_PHONE_STATE_CHANGED);
//registerReceiver(receiver,filter); //- registered in manifest - wont work when registered in code
//sending to specific receiver - explicit intent
Intent intent = new Intent(this, MyReceiver.class);
sendBroadcast(intent);
}
@Override
protected void onPause()
{
unregisterReceiver(receiver);
super.onPause();
}
}
HERE IS MY SERVICE
package com.example.hdm.globalreciever;
import android.app.IntentService;
import android.content.Intent;
import android.content.Context;
import android.support.v4.content.LocalBroadcastManager;
/**
* An {@link IntentService} subclass for handling asynchronous task requests in
* a service on a separate handler thread.
*
* TODO: Customize class - update intent actions, extra parameters and static
* helper methods.
*/
public class MyIntentService extends IntentService {
public MyIntentService() {
super("MyIntentService");
}
@Override
protected void onHandleIntent(Intent intent) {
Intent myIntent = new Intent();
myIntent.setAction("android.intent.action.PHONE_STATE");
LocalBroadcastManager.getInstance(this).sendBroadcast(myIntent);
}
}
HERE IS ME RECEIVER
package com.example.hdm.globalreciever;
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 MyReceiver extends BroadcastReceiver {
public MyReceiver() {
}
@Override
public void onReceive(Context context, Intent intent) {
// TODO: This method is called when the BroadcastReceiver is receiving
// an Intent broadcast.
Log.e("Received a BroadCast","intent "+intent.getAction());
Log.e("Received a BroadCast","intent "+intent.getStringExtra(TelephonyManager.EXTRA_STATE));
//Receiver
Toast.makeText(context, "Incoming phone call", Toast.LENGTH_LONG).show();
}
}