Services in Android is not getting Started in BroadCast receiver - android

I am trying to make an android app that must do some database activities like storing phone number and name etc in the SQLite DB . This all Data Base stuff is done as a service. The service must start as soon as the call comes and when the call ends the stored details must be showed to user as soon as the call ends. For this purpose I am using Broad Cast Receiver. I have also provide the following codes which I have used in my app.
MyServices.java
public class MyServices extends Service {
TelephonyManager Tel;
MyPhoneStateListener MyListener;
RB_SIGNAL_STRENGTH signalobj = new RB_SIGNAL_STRENGTH();
RB_DatabaseHandler db = new RB_DatabaseHandler(getApplicationContext());
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
isMyServiceRunning();
MyListener = new MyPhoneStateListener();
Tel = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
Tel.listen(MyListener, PhoneStateListener.LISTEN_SIGNAL_STRENGTHS);
super.onCreate();
Log.i("Serv","Service Started");
return super.onStartCommand(intent, flags, startId);
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
db.close_DB();
Log.i("Serv","Service Stopped");
super.onDestroy();
}
MyReceiver.java
public class MyPhoneReceiver extends BroadcastReceiver {
String state=null;
#Override
public void onReceive(Context context, Intent intent) {
Bundle extras = intent.getExtras();
if (state.equalsIgnoreCase(TelephonyManager.EXTRA_STATE_OFFHOOK))
{
try{
Intent i = new Intent(context,MyServices.class);
Log.i("Recv", "In Try");
context.startService(i);
}
catch(Exception e)
{
Log.d("Recv", "Service not starting");
}
}//End if offhook
if(state.equals(TelephonyManager.EXTRA_STATE_IDLE))
{
Log.i("Recv","CALL ENDED");
try
{
Intent i = new Intent(context,EndActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
catch(Exception e){
Log.d("Recv", "Activity not starting");
}
}
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.testapp"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="9" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" >
</uses-permission>
<uses-permission android:name="android.permission.SIGNAL_PERSISTENT_PROCESSES" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<activity android:name="StartActivity" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="EndActivity" >
</activity>
<receiver android:name=".MyReceiver" >
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE" >
</action>
</intent-filter>
</receiver>
<service
android:name="MyServices"
></service>
</application>

Your class name is MyPhoneReceiver but in your Manifest you are using MyReceiver, these two names must match exactly.
Addition
I just noticed that you are trying to instantiate your database before the Service has a valid Context. This will probably throw an exception in MyServices:
RB_DatabaseHandler db = new RB_DatabaseHandler(getApplicationContext());
You can to declare db as a field variable but leave it null:
RB_DatabaseHandler db;
And inside a method like onStartCommand() initialize it:
db = new RB_DatabaseHandler(getApplicationContext());
Lastly, calling fundamental methods like onCreate() out of order usually creates problems, this is not recommended in onStartCommand():
super.onCreate();

because state variable is null
public class MyPhoneReceiver extends BroadcastReceiver {
String state=null;
#Override
public void onReceive(Context context, Intent intent) {
Bundle extras = intent.getExtras();
state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
//your code here...

Related

Broadcastreceiver not receiving?

I am trying to pass values from service to activity using broadcast
I am using following code to call broadcast in service
Intent i = new Intent();
i.putExtra("test",result);
sendBroadcast(i);
And receiving in main activity using following code
public class myreciver extends BroadcastReceiver{
public String data =null;
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
String datapassed = intent.getStringExtra("test");
}
}
In Main Activity
myreciver m = new myreciver();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(MyService.MY_ACTION);
registerReceiver(m, intentFilter);
but my receiver is not called.
Manifest file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.pragadees.restex" >
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
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=".MainActivity$myreciver" >
</receiver>
<service
android:name=".MyIntentService"
android:exported="false" >
</service>
<service
android:name=".MyService"
android:enabled="true"
android:exported="false" >
</service>
<activity
android:name=".display"
android:label="#string/title_activity_display" >
</activity>
</application>
</manifest>
Action missing in Intent which is passing to sendBroadcast method.do it as:
Intent i = new Intent(MyService.MY_ACTION); //<< pass Action to Intent
i.putExtra("test",result);
sendBroadcast(i);
use broad cast like this
Intent i = new Intent("Broadcastname");
context.sendBroadcast(i);
and now receive broad cast like this way
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
IntentFilter intentFilter = new IntentFilter("Broadcastname");
BroadcastReceiver Receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
// to your work here
}
});
}
};
this.registerReceiver(Receiver, intentFilter);
finally unregister in onstop() method
#Override
protected void onStop() {
// TODO Auto-generated method stub
if (Receiver != null) {
this.unregisterReceiver(this.Receiver);
}
super.onStop();
}
Android's BroadcastReceiver is part of a framework that allows activities and services to send data to one another, even if they belong to separate apps. This is how apps share data with one another, such as when you share a picture from your gallery to Facebook or G+. However, this extensive capability means that you have to be careful about how you filter your requests, which means that it can be harder to just send a quick message from inside your own app.
If you don't need to worry about receiving data from other apps, then you can use the LocalBroadcastManager, which is an implementation of BroadcastReceiver that is confined inside of your own app's jurisdiction. It can't send or receive intents from outside your app. Its interface is nearly identical to BroadcastReceiver's:
public class MyActivity extends Activity {
private LocalBroadcastManager mBroadcastManager;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mBroadcastManager = LocalBroadcastManager.getInstance(this);
//Build an intent filter so you only receive relevant intents
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("Test from Service to Activity");
//Register a new BroadcastReceiver with the LocalBroadcastManager
mBroadcastManager.registerReceiver(new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
String dataPassed = intent.getStringExtra("test");
}
}, intentFilter);
//If you ever want to send a broadcast, use this:
Intent sendIntent = new Intent(this, MyService.class);
sendIntent.setAction("Test from Activity to Service");
sendIntent.putExtra("test", "This is a test from Activity!");
mBroadcastManager.sendBroadcast(sendIntent);
}
}
//Then in your Service...
public class MyService extends Service {
private LocalBroadcastManager mBroadcastManager;
public void onCreate() {
mBroadcastManager = LocalBroadcastManger.getInstance(this);
}
public int onStartCommand(Intent intent, int flags, int startId) {
//Build intent filter
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("Test from Activity to Service");
mBroadcastManger.registerReceiver(new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
String dataPassed = intent.getStringExtra("test");
}
}, intentFilter);
//To send data to the activity:
Intent sendIntent = new Intent(this, MyActivity.class);
sendIntent.setAction("Test from Service to Activity");
sendIntent.putExtra("test", "This is a test from Service!");
mBroadcastManager.sendBroadcast(sendIntent);
}
}

Android-Boot Completed is not working in Broadcastreceiver

I'm using android(version 4.1.1) MeLE box(SmartTv) for developing one application, i need to start up my application when device Boot Time is completed but my device not catch up the BOOT_COMPLETED Action. If i'm use that same application in mobiles or emulator the Boot_Completion action were caught by Broadcast_receiver.
if anyone known about this issue help me thanks in advance....
here is my code...
manifest:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<receiver android:name=".BootCompletedReceiver" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.QUICKBOOT_POWERON" />
</intent-filter>
</receiver>
<service android:name="NotifyingDailyService" >
</service>
BootCompletedReceiver class:
public class BootCompletedReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent arg1) {
// TODO Auto-generated method stub
Log.w("boot_broadcast_poc", "starting service...");
context.startService(new Intent(context, NotifyingDailyService.class));
}
}
Service class:
public class NotifyingDailyService extends Service {
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public int onStartCommand(Intent pIntent, int flags, int startId) {
// TODO Auto-generated method stub
Toast.makeText(this, "NotifyingDailyService", Toast.LENGTH_LONG).show();
Log.i("com.example.bootbroadcastpoc","NotifyingDailyService");
return super.onStartCommand(intent, flags, startId);
}
}
One thing I noticed is you don't have the category set for your receiver in your Manifest. The following works for me in my App.
<receiver android:name="us.nineworlds.serenity.StartupBroadcastReceiver" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
Then in my StartupBroadcastReceiver, i have the following
public void onReceive(Context context, Intent intent) {
if (intent.getAction() == null) {
return;
}
if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED")) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
boolean startupAfterBoot = prefs.getBoolean("serenity_boot_startup", false);
if (startupAfterBoot) {
Intent i = new Intent(context, MainActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
}
}
This will start the MainActivity class once bootup has been completed.
Link to the project code is here: https://github.com/NineWorlds/serenity-android/blob/master/serenity-app/src/main/java/us/nineworlds/serenity/StartupBroadcastReceiver.java

BroadcastReceiver for Screen On/Off not working

I am trying to use BroadcastReceiver but it is not working, please help me to solve this problem.
MyReceiver.java
package com.example.broadcast_receiver;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
public class MyReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Log.i("[BroadcastReceiver]", "MyReceiver");
if(intent.getAction().equals(Intent.ACTION_SCREEN_ON)){
Log.i("[BroadcastReceiver]", "Screen ON");
}
else if(intent.getAction().equals(Intent.ACTION_SCREEN_OFF)){
Log.i("[BroadcastReceiver]", "Screen OFF");
}
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.broadcast_receiver"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="9"
android:targetSdkVersion="16" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<receiver android:name=".MyReceiver"
android:enabled="true"
android:exported="false">
<intent-filter>
<action android:name="android.intent.action.SCREEN_ON"/>
<action android:name="android.intent.action.SCREEN_OFF"/>
</intent-filter>
</receiver>
<activity
android:name="com.example.broadcast_receiver.MainActivity"
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>
BroadcastReceiver not working and not making any log, please help me to solve this problem.
Hey try using dynamic calling of broadcast,I tried this it will surly work...
public class MainActivity extends Activity {
//Create broadcast object
BroadcastReceiver mybroadcast = new BroadcastReceiver() {
//When Event is published, onReceive method is called
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Log.i("[BroadcastReceiver]", "MyReceiver");
if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
Log.i("[BroadcastReceiver]", "Screen ON");
}
else if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
Log.i("[BroadcastReceiver]", "Screen OFF");
}
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
registerReceiver(mybroadcast, new IntentFilter(Intent.ACTION_SCREEN_ON));
registerReceiver(mybroadcast, new IntentFilter(Intent.ACTION_SCREEN_OFF));
}
}
If you want this receiver to be called by the system, you would need to export it. You set exported = "false", change this to true or remove exported entirely and this will start working. Normally this would be insecure, but as both SCREEN_ON and SCREEN_OFF are protected-broadcasts, and you verify the actions, only more trusted system code can send them too you, so it's pretty safe.
Sadly this wont work in this case as the intents broadcast have the following flags:
Intent.FLAG_RECEIVER_REGISTERED_ONLY | Intent.FLAG_RECEIVER_FOREGROUND
Can you try with getting battery value:
public class Broadcast extends Activity {
//Create broadcast object
BroadcastReceiver mybroadcast = new BroadcastReceiver() {
//When Event is published, onReceive method is called
#Override
public void onReceive(Context context, Intent intent) {
//Get battery percentage
int batterylevel = intent.getIntExtra("level", 0);
//get progressbar
ProgressBar myprogressbar = (ProgressBar) findViewById(R.id.progressbar);
myprogressbar.setProgress(batterylevel);
TextView tv = (TextView) findViewById(R.id.textfield);
//Set TextView with text
tv.setText("Battery Level: " + Integer.toString(batterylevel) + "%");
}
});
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_broadcast);
registerReceiver(mybroadcast, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
}
}

BroadcastReceiver not receiving

I have read the instructions and examples in SO questions, but still unable to implement a simple BroadcastReceiver, it simply does not receive anything, can someone kindly provide some advice on the following code?
tnx
My activity:
public class Receiver1Activity 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(MyService.MY_ACTION);
registerReceiver(new MyReceiver(), filter);
Intent intent = new Intent();
startService(intent);
}
}
My receiver:
public class MyReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context arg0, Intent arg1) {
Log.i("MyReceiver", "onreceive");
}
}
My service, which sends the broadcast:
public class MyService extends Service {
public static final String MY_ACTION = "com.receiver1.myaction";
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Intent intent2 = new Intent(MY_ACTION);
sendBroadcast(intent2);
return START_NOT_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
My manifest file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.receiver1"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="10" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<activity
android:name=".Receiver1Activity"
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=".MyService"></service>
</application>
</manifest>
Are you sure that your service is even getting started? It looks like your just creating a blank intent and calling startService().
Your broadcastReceiver appears to be correct.
You need to register your receiver in your AndroidManifest.xml. Until you do that, the Android OS won't be able to find your BroadcastReceiver.

SMS type TEXT or MMS or other?

How to capture incoming MESSAGE type whether it is Text or MMS or something else in Android programmatic ally?
earlier i came here for solution but didn't get.
now i have solved it and decided to post answer myself.
if you want to know message type is Text or MMS?
create an Activity where we will start a Service
public class ListenSMSActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//start the service to listen
startService(new Intent(getBaseContext(),ListenSMSService.class));
}}
create a service where we will use content Observer
public class ListenSMSService extends Service{
//Context globalContext;
ContentResolver contentResolver;
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
registerObserver();
}
public void registerObserver() {
contentResolver = getContentResolver();
contentResolver.registerContentObserver(Uri.parse
("content://mms-sms/conversations/"), true,
new MyObserver(new Handler()));
Log.v("Debug", " in registerObserver method.........");
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
class MyObserver extends ContentObserver
{
public MyObserver(Handler handler) {
super(handler);
// TODO Auto-generated constructor stub
}
#Override
public void onChange(boolean selfChange) {
super.onChange(selfChange);
Log.v("Current Locaion", "in onChange method....");
final String[] projection = new String[]{"_id", "ct_t"};
Uri uri = Uri.parse("content://mms-sms/conversations/");
Cursor query = contentResolver.query(uri, projection, null, null, null);
query.moveToFirst();
String string = query.getString(query.getColumnIndex("ct_t"));
if ("application/vnd.wap.multipart.related".equals(string))
{
// it's MMS
Log.v("Debug", "it's MMS");
}
else
{
// it's SMS
Log.v("Debug", "it's SMS");
}
}
}
}
and finally add permissions and make entry for service in manifest file
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.rdc"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="8" />
<uses-permission android:name="android.permission.SEND_SMS"></uses-permission>
<uses-permission android:name="android.permission.RECEIVE_SMS"></uses-permission>
<uses-permission android:name="android.permission.READ_SMS"></uses-permission>
<application android:icon="#drawable/icon" android:label="#string/app_name">
<activity android:name="com.rdc.ListenSMSActivity"
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:enabled="true" android:name="com.rdc.ListenSMSService">
<intent-filter>
<action android:name="com.kns.ListenSMSService">
</action>
</intent-filter>
</service>
</application>
</manifest>
you will get the message type (sms/mms) in Logcat.

Categories

Resources