We have a requirement to show an acknoldgement screen after user share some texts on Messaging apps such as Whatsapp, Telegram, SMS etc..
We have been using the react-native-share library for this and it works fine on non Huawei devices. However, Huawei devices doesn't return success/failure when user share hence the app gives issues on Huawei devices.
Upon checking the react-native-share library internal codes, it seems the BroadcastReceiver onReceive method does not get triggered when user choose and app on HuaweiChooser.
I created the following sample code to simulate this and on Non-Huawei devices this code's onReceive method get triggered but not in Huawei devices.
Appreciate any help regarding this.
This is the Sample code
MainActivity.java
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.content.IntentSender;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button shareButton = findViewById(R.id.button);
shareButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent chooser;
IntentSender intentSender = MyReceiver.getIntentSender(getApplicationContext());
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, "This is my text to send.");
sendIntent.setType("text/plain");
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP_MR1) {
chooser = Intent.createChooser(sendIntent,"Sharing Rocks",intentSender);
chooser.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
}else{
chooser = Intent.createChooser(sendIntent,"Sharing Rocks");
}
startActivityForResult(chooser, 1234);
}
});
}
}
Receiver.Java
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.IntentSender;
import android.widget.Toast;
public class MyReceiver extends BroadcastReceiver {
private static MyReceiver myReceiver;
private static final String EXTRA_RECEIVER_TOKEN = "receiver_token";
public static IntentSender getIntentSender(Context context){
String intentAction = context.getPackageName()+"_ACTION";
myReceiver = new MyReceiver();
context.registerReceiver(myReceiver, new IntentFilter(intentAction));
Intent intent = new Intent(intentAction);
intent.setPackage(context.getPackageName());
intent.putExtra(EXTRA_RECEIVER_TOKEN,myReceiver.hashCode());
PendingIntent callback = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
return callback.getIntentSender();
}
#Override
public void onReceive(Context context, Intent intent) {
System.out.println("//// Inside onReceive");
ComponentName target = intent.getParcelableExtra(Intent.EXTRA_CHOSEN_COMPONENT);
System.out.println("//// target : " + target);
}
}
Manifest File
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.lk.infinitx.huaweisharetest">
<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/Theme.HuaweiShareTest">
<receiver
android:name=".MyReceiver"
android:enabled="true"
android:exported="true"></receiver>
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
I change chooser title with "null" and my problem solved.
val chooser = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
Intent.createChooser(sendIntent, null, pendingIntent.intentSender)
} else {
Intent.createChooser(sendIntent, null)
}
Related
I am working on an app in react native. I am searching for a code when my app is in the background or has killed. I want a service like notifcationListnerService which invokes the app again. want a similar service that is always running and when a user copies something it will show a push notification to the user like that you have copied something.
Here is what I have tried but these are too complex to understand because these are in java.
Android ClipBoard Manager
Android ClipBoard With Example
This question from StackOverflow also does not have any answer
A solution for GitHub but too complex
one thing I didn't need #react-native-community/clipboard or something like this. the thing that I need is to show push notification on copying something for any app installed of the device.
So Finally searching for two days finally I have implemented what I want. I am showing a toast, not a notification(will implement it later). I am sharing my code but still, I have a problem when my application restart its service for clipboard manager the service is running as I see it in the logcat. Here is my code.
ClipboardMonitorService.java
package com.wm;
import android.app.Service;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Intent;
import android.os.Environment;
import android.os.IBinder;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.Date;
public class ClipboardMonitorService extends Service {
private static final String TAG = "ClipboardManager";
private static final String FILENAME = "clipboard-history.txt";
private File mHistoryFile;
private ExecutorService mThreadPool = Executors.newSingleThreadExecutor();
private ClipboardManager mClipboardManager;
#Override
public void onCreate() {
super.onCreate();
Log.e("service is running","service is running");
// TODO: Show an ongoing notification when this service is running.
mHistoryFile = new File(getExternalFilesDir(null), FILENAME);
mClipboardManager =
(ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
mClipboardManager.addPrimaryClipChangedListener(
mOnPrimaryClipChangedListener);
}
#Override
public void onDestroy() {
super.onDestroy();
if (mClipboardManager != null) {
mClipboardManager.removePrimaryClipChangedListener(
mOnPrimaryClipChangedListener);
}
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
private boolean isExternalStorageWritable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
return true;
}
return false;
}
private ClipboardManager.OnPrimaryClipChangedListener mOnPrimaryClipChangedListener =
new ClipboardManager.OnPrimaryClipChangedListener() {
#Override
public void onPrimaryClipChanged() {
Log.d(TAG, "onPrimaryClipChanged");
ClipData clip = mClipboardManager.getPrimaryClip();
mThreadPool.execute(new WriteHistoryRunnable(clip.getItemAt(0).getText()));
Log.e("Copied Text","hahah"+clip.getItemAt(0).getText());
Toast.makeText(getApplicationContext(),"My App toast",Toast.LENGTH_SHORT).show();
}
};
private class WriteHistoryRunnable implements Runnable {
private final Date mNow;
private final CharSequence mTextToWrite;
public WriteHistoryRunnable(CharSequence text) {
mNow = new Date(System.currentTimeMillis());
mTextToWrite = text;
}
#Override
public void run() {
if (TextUtils.isEmpty(mTextToWrite)) {
// Don't write empty text to the file
return;
}
if (isExternalStorageWritable()) {
try {
Log.i(TAG, "Writing new clip to history:");
Log.i(TAG, mTextToWrite.toString());
BufferedWriter writer =
new BufferedWriter(new FileWriter(mHistoryFile, true));
writer.write(String.format("[%s]: ", mNow.toString()));
writer.write(mTextToWrite.toString());
writer.newLine();
writer.close();
} catch (IOException e) {
Log.w(TAG, String.format("Failed to open file %s for writing!",
mHistoryFile.getAbsoluteFile()));
}
} else {
Log.w(TAG, "External storage is not writable!");
}
}
}
}
This is used for when the app is closed or the device is restarted then it will start the service again.
BootUpRecever.java
package com.wm;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
public class BootUpReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction() == Intent.ACTION_BOOT_COMPLETED){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//log("Starting the service in >=26 Mode from a BroadcastReceiver")
context.startForegroundService(new Intent(context, ClipboardMonitorService.class));
return;
}
//log("Starting the service in < 26 Mode from a BroadcastReceiver")
context.startService(new Intent(context, ClipboardMonitorService.class));
}
}
}
to start the activity as the app start
MainActivity.java
package com.wm;
import android.content.Intent;
import android.os.Bundle;
import com.facebook.react.ReactActivity;
public class MainActivity extends ReactActivity {
#Override
protected String getMainComponentName() {
return "wm";
}
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// TODO: Show the contents of the clipboard history.
startService(new Intent(this, ClipboardMonitorService.class));
}
}
Here are the permissions and to start the service
AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.wm">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<application
android:name=".MainApplication"
android:label="#string/app_name"
android:icon="#mipmap/ic_launcher"
android:roundIcon="#mipmap/ic_launcher_round"
android:allowBackup="true"
android:theme="#style/AppTheme">
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:configChanges="keyboard|keyboardHidden|orientation|screenSize|uiMode"
android:launchMode="singleTask"
android:windowSoftInputMode="adjustResize">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="com.facebook.react.devsupport.DevSettingsActivity" />
<service
android:name=".ClipboardMonitorService"
android:label="Clipboard Monitor"
android:exported="false"/>
<receiver
android:name=".BootUpReceiver"
android:enabled="true"
android:permission="android.permission.RECEIVE_BOOT_COMPLETED">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
</application>
</manifest>
I am following this answer to implement app un-install detector. I am basically trying to open Main Activity when un-installation event is detected, but when I un-istall my app nothing happens (Main Activity does not open before un-install).
Please help, what is wrong with my code?
MainAcivity:
package com.example.appdeveloper.unistalltest;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
Broadcast Receiver:
package com.example.appdeveloper.unistalltest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
public class UninstallIntentReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// fetching package names from extras
String[] packageNames = intent.getStringArrayExtra("android.intent.extra.PACKAGES");
if(packageNames!=null){
for(String packageName: packageNames){
if(packageName!=null && packageName.equals("com.example.appdeveloper.unistalltest")){
// User has selected our application under the Manage Apps settings
// now initiating background thread to watch for activity
new ListenActivities(context).start();
}
}
}
else {
Toast.makeText(context, "No package found in Broadcast Receiver", Toast.LENGTH_LONG).show();
}
}
}
ListenActivities.java:
package com.example.appdeveloper.unistalltest;
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;
import java.util.List;
public class ListenActivities extends Thread {
boolean exit = false;
ActivityManager am = null;
Context context = null;
public ListenActivities(Context con){
context = con;
am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
}
public void run(){
Looper.prepare();
while(!exit){
// get the info from the currently running task
List< ActivityManager.RunningTaskInfo > taskInfo = am.getRunningTasks(MAX_PRIORITY);
String activityName = taskInfo.get(0).topActivity.getClassName();
Log.d("topActivity", "CURRENT Activity ::"
+ activityName);
if (activityName.equals("com.android.packageinstaller.UninstallerActivity")) {
// User has clicked on the Uninstall button under the Manage Apps settings
//do whatever pre-uninstallation task you want to perform here
// show dialogue or start another activity or database operations etc..etc..
context.startActivity(new Intent(context, MainActivity.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
exit = true;
Toast.makeText(context, "Done with preuninstallation tasks... Exiting Now", Toast.LENGTH_LONG).show();
}
else if(activityName.equals("com.android.settings.ManageApplications")) {
// back button was pressed and the user has been taken back to Manage Applications window
// we should close the activity monitoring now
exit=true;
}
}
Looper.loop();
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.appdeveloper.unistalltest">
<uses-permission android:name="android.permission.GET_TASKS"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
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=".UninstallIntentReceiver">
<intent-filter android:priority="0">
<action android:name="android.intent.action.QUERY_PACKAGE_RESTART" />
<data android:scheme="package" />
</intent-filter>
</receiver>
</application>
</manifest>
Your app can't know when the user uninstall it since Android 4.0+. I had a similar problem, but didn't found a way to do it. The only things I found today (i already gave up with my app, but maybe it can help you) is this: https://developer.android.com/guide/topics/admin/device-admin.html
I'm not sure this will help you, but it is the only thing i found.
I have an app that before worked fine but recently won't run.
Before it only had offline features, the most complex would be the local notification - but I need to add a GCM functionality to it. I searched for answers but it's so difficult to understand.
I tried to copy the code of a tutorial I've seen. I learned that I need a thing called GCMRegistrar but I don't know where to get it. Then I tested my app, there were errors of course because I don't have the gcmregistrar.
What I did is I enclosed the code in a comment block and ran the app again. That's when my app won't run anymore. After a few days of this mishap, I decided to create another app where I would put all the offline feature of my app. after that copying and pasting, I tried to run my the new app but it also won't run.
I've searched for ways to fix it and found a few fixes. Those fix works for other apps but won't work for my new app.
Here's my MainActivity.java, this one has the local notification
package com.example.mypower_build101;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity {
Button addDevice, showDevice, showDialog;
String[] arrContentTxt;
final Context ctx = this;
int notifCount;
int x = 0;
Handler notifLauncher, notifStopper;
String contentTxt;
Resources res = getResources();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addDevice = (Button)findViewById(R.id.btnAddDevice);
showDevice = (Button)findViewById(R.id.btnShowDevice);
showDialog = (Button)findViewById(R.id.btnShowDialog);
arrContentTxt = res.getStringArray(R.array.notifContentText);
//contentTxt = arrContentTxt[1];
showDialog.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
/*DialogFragment diag = new SwitchCheckChange();
diag.show(getFragmentManager(), "cbo Click");*/
showNotif();
}
});
useNotifLauncher();
useNotifStopper();
}
public void useNotifLauncher(){
notifLauncher = new Handler();
notifLauncher.postDelayed(runNotif, 50000);
}
public Runnable runNotif = new Runnable(){
#Override
public void run() {
showNotif();
notifLauncher.postDelayed(runNotif, 50000);
}
};
public void useNotifStopper(){
notifStopper = new Handler();
notifStopper.postDelayed(stopNotif, 40000);
}
public Runnable stopNotif = new Runnable(){
#Override
public void run() {
cancelNotification(x);
notifStopper.postDelayed(stopNotif, 40000);
}
};
public void addClick(View v){
Intent i = new Intent(this, AddDeviceForm.class);
startActivity(i);
}
public void showClick(View v){
Toast.makeText(getBaseContext(), "Please wait...", Toast.LENGTH_LONG).show();
Intent i = new Intent(this, ListViewForm.class);
startActivity(i);
}
public void showNotif(){
Uri notifSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Intent i = new Intent(MainActivity.this, NotifReceiver.class);
PendingIntent pi = PendingIntent.getActivity(MainActivity.this, 0, i, 0);
//String[] notifTitle = R.array.notifTitle;
Notification notif = new Notification.Builder(this)
.setContentTitle("MyPower Reminder")
.setContentText("Unplug unused appliances and chargers")
//.setContentText(contentTxt)
.setSmallIcon(R.drawable.ic_launcher)
.setContentIntent(pi)
.setSound(notifSound)
.addAction(0, "View Full Reminder", pi)
.build();
NotificationManager notifMgr = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
notifMgr.notify(0, notif);
}
public void cancelNotification(int notificationId){
if (Context.NOTIFICATION_SERVICE!=null) {
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager nMgr = (NotificationManager) getApplicationContext().getSystemService(ns);
nMgr.cancel(notificationId);
}
}
}
here's my androidmanifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.mypower_build101"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="16"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="#drawable/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>
<activity
android:name=".AddDeviceForm"
android:label="#string/title_activity_add_device_form" >
</activity>
<activity
android:name=".ListViewForm"
android:label="#string/title_activity_list_view_form" >
</activity>
<activity
android:name=".NotifReceiver"
android:label="#string/title_activity_notif_receiver" >
</activity>
</application>
</manifest>
I'm not putting everything here because it would be to lengthy and I think the problems might be at the MainActivity or the android manifest.
If you could teach me how use the gcm thing that would be very, very, much appreciated.
Hi guys for some reason my post have an error so please use and look at this document. here's the document link
https://www.dropbox.com/s/tc2j2a2pan53r96/Ricky%20Manalo%20LogCat%20Log.docx?dl=0
I am trying to create a Service application without a UI/Activity.
The service will start on BOOT_COMPLETED. Currently I am experiencing an issue when the receiver service cannot start the main service.
The error sound like that (Android Device Monitor):
Tag: Activity Manager
Text: Unable to start service Intent { cmp=com.remote.cat/.ActionService } U=0: not found
My android OS version on the device is 4.2.2
I am testing it via this command in PowerShell:
adb.exe shell am broadcast -a android.intent.action.BOOT_COMPLETED -n com.remote.cat/.AutoStartServiceReceiver
Both services are in the root of the package com.remote.cat
Feel like I am missing a small thing or having a typo, would greatly appreciate any help!
Thank you!
Here is the code of the manifest:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.remote.cat"
android:installLocation="internalOnly">
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application android:allowBackup="true" android:label="#string/app_name"
android:icon="#mipmap/ic_launcher" android:theme="#style/AppTheme">
<receiver android:name="com.remote.cat.AutoStartServiceReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
</application>
<service android:name="com.remote.cat.AutoStartServiceReceiver"></service>
<service android:name="com.remote.cat.ActionService"></service>
</manifest>
Here is the brodcastreceiver class:
package com.remote.cat;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class AutoStartServiceReceiver extends BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent)
{
if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED))
{
Intent serviceIntent = new Intent(context, ActionService.class);
//Intent serviceIntent = new Intent("com.remote.cat.ActionService");
context.startService(serviceIntent);
}
}
}
Here is the main service that I am trying to start:
package com.remote.cat;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;
import java.util.TimerTask;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class ActionService extends Service
{
private ScheduledThreadPoolExecutor executor = null;
#Override
public IBinder onBind(Intent intent)
{
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
executor = new ScheduledThreadPoolExecutor(4);
final ScheduledFuture<?> handle = executor.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "one minute message", Toast.LENGTH_LONG).show();
}
}, 0, 8, TimeUnit.SECONDS);
return START_STICKY;
}
}
Change your AutoStartServiceReceiver declaration in the manifest to be a <receiver> rather than <service>.
The error is in your broadcastreceiver class
if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED))
it should be
if(intent.getAction().equals("android.intent.action.BOOT_COMPLETED"))
EDIT
I believe you have to declare your services inside the application tag since it is a part of the application
I know the AlarmManagerBroadcastReceiver will stay system to keep watch over SMS after I installed the .apk
Will the AlarmManagerBroadcastReceiver expend battery even if I never receive s SMS?
Do I need disable the AlarmManagerBroadcastReceiver when I stop watch SMS ?
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.enabledisablebroadcastreceiver"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="8" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.code4reference.enabledisablebroadcastreceiver.EnableDisableBroadcastReceiver"
android:label="#string/title_activity_enable_disable_boradcast_receiver" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<!-- Broadcast receiver -->
<receiver android:name="com.code4reference.enabledisablebroadcastreceiver.AlarmManagerBroadcastReceiver" >
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
<service android:name="com.code4reference.enabledisablebroadcastreceiver.MyInternetServer"></service>
</application>
<uses-permission android:name="android.permission.SEND_SMS"/>
<uses-permission android:name="android.permission.RECEIVE_SMS"/>
</manifest>
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.SmsMessage;
import android.util.Log;
public class AlarmManagerBroadcastReceiver extends BroadcastReceiver {
private static final String ACTION = "android.provider.Telephony.SMS_RECEIVED";
#Override
public void onReceive(Context context, Intent intent) {
if (intent != null && intent.getAction() != null && ACTION.compareToIgnoreCase(intent.getAction()) == 0) {
Object[] pduArray = (Object[]) intent.getExtras().get("pdus");
SmsMessage[] messages = new SmsMessage[pduArray.length];
for (int i = 0; i < pduArray.length; i++) {
messages[i] = SmsMessage.createFromPdu((byte[]) pduArray[i]);
//Log.d("CWCGR1",
// "From: " + messages[i].getOriginatingAddress()+
// " Msg: " + messages[i].getMessageBody());
HandleMsg(context,messages[i].getOriginatingAddress(), messages[i].getMessageBody());
}
}
}
private void HandleMsg(Context context,String address, String body ){
Intent msgIntent = new Intent(context,MyInternetServer.class);
msgIntent.putExtra("address", address);
msgIntent.putExtra("body", body);
context.startService(msgIntent);
}
}
import com.example.enabledisablebroadcastreceiver.R;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class EnableDisableBroadcastReceiver extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnExit=(Button)findViewById(R.id.btnExit);
btnExit.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
finish();
}
});
}
public void enableBroadcastReceiver(View view){
ComponentName receiver = new ComponentName(this, AlarmManagerBroadcastReceiver.class);
PackageManager pm = this.getPackageManager();
pm.setComponentEnabledSetting(receiver,
PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
PackageManager.DONT_KILL_APP);
Toast.makeText(this, "Enabled broadcast receiver", Toast.LENGTH_SHORT).show();
}
public void disableBroadcastReceiver(View view){
ComponentName receiver = new ComponentName(this, AlarmManagerBroadcastReceiver.class);
PackageManager pm = this.getPackageManager();
pm.setComponentEnabledSetting(receiver,
PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
PackageManager.DONT_KILL_APP);
Toast.makeText(this, "Disabled broadcst receiver", Toast.LENGTH_SHORT).show();
}
}
As discussed here, an incoming SMS belongs to a special group of low-level system events that will cause the CPU to wake from the battery-saving "sleep mode" (this group includes incoming calls, incoming mobile data packets and AlarmManager events). The device's GSM radio will listen to incoming SMS regardless of your broadcast receiver being set or not. When an SMS arrives, the system will choose which receiver(s) will handle it. Thus, having a SMS broadcast receiver registered has no impact in the battery consumption. Besides, energy consumption due to a registered receiver in memory is not significant.
You can unregister the broadcast receiver programmatically if there is a functional requirement to do so.
Because you have fined your AlarmManagerBroadcastReceiver in the android manifest, android will wake up your app and call the AlarmManagerBroadcastReceiver every time an sms is received.
If no SMS are received, your app won't be woken up so there won't be any impact on battery.
If you want control over when to receive those broadcasts, register and unregister your receiver programmatically through the registerReceiver(BroadcastReceiver receiver, IntentFilter filter) method on a Context (e.g. Activity).