I have been working on an application that use to receive SMS and show a Toast using Broadcast Receiver and i have an activity with no purpose, when i removed that activity and build the apk and run on my phone, application is not responding when SMS is received (no Toast showing), although remaining code is same as it was previously. Can anyone help please i am so stuck and couldn't help myself reading hundreds of answers. I studied i should create a service but still no Toast is appearing. below is my code. I can not have any GUI in my application even don't want to have auto kill activity.
BroadcastReceiver.java
package com.test.testservice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.widget.Toast;
public class SmsReceiver extends BroadcastReceiver {
public static final String SMS_BUNDLE = "pdus";
private static final String LOG = "SmsBroadcastReceiver";
#Override
public void onReceive(Context context, Intent intent) {
Bundle intentExtras = intent.getExtras();
if (intentExtras != null) {
Object[] sms = (Object[]) intentExtras.get(SMS_BUNDLE);
if (sms != null)
{
String smsMessageStr = "";
for (int i = 0; i < sms.length; ++i)
{
SmsMessage smsMessage = SmsMessage.createFromPdu((byte[]) sms[i]);
String smsBody = smsMessage.getMessageBody().toString();
String address = smsMessage.getOriginatingAddress();
smsMessageStr += "SMS From: " + address + "\n";
smsMessageStr += smsBody + "\n";
}
Toast.makeText(context, smsMessageStr, Toast.LENGTH_LONG).show();
//MyService objService=new MyService();
//objService.startService(intent);
//objService.stopService(intent);
Intent myIntent = new Intent(context, MyService.class);
//myIntent.putExtra("Sender", Sender);
//myIntent.putExtra("Fullsms", Fullsms);
context.startService(myIntent);
}
}
}
}
MyService.java
package com.test.testservice;
import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;
import android.widget.Toast;
public class MyService extends Service {
private static final String LOG = "MyService";
#Override
public boolean stopService(Intent name) {
if (super.stopService(name))
{
Toast.makeText(this,"HELLO stopService",Toast.LENGTH_LONG).show();
Log.i(LOG, "stopService");
return true;
}
else return false;
}
#Override
public ComponentName startService(Intent service) {
return super.startService(service);
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
Toast.makeText(this,"HELLO onCreate",Toast.LENGTH_LONG).show();
}
#Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
Toast.makeText(this,"HELLO onStart",Toast.LENGTH_LONG).show();
}
}
AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.test.testservice">
<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/AppTheme">
<receiver android:name=".SmsReceiver" android:enabled="true" android:exported="true">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
<action android:name="android.intent.action.BOOT_COMPLETED"/>
<action android:name="android.intent.action.REBOOT"/>
</intent-filter>
</receiver>
</application>
<service android:name="com.test.testservice.service.MyService"/>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.WRITE_SMS" />
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
</manifest>
Unless you are creating your own phone, or your own custom ROM, you need the activity. Your BroadcastReceiver will not work when your app is first installed. It will only start to work once the user has launched your activity (or something else uses an explicit Intent to start one of your components).
I can not have any GUI in my application
Then your app will not work on Android 3.1+ devices, which make up the vast majority of the Android device ecosystem.
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 trying to make a simple app which will notify if there is internet connection available or not on internet connectivity change. i have found some solution on internet and tries to implement them but somehow its not working. my broadcast receiver which i have registered on my manifest file is not calling on network connectivity change.
Manifest
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<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/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=".NetworkStateChangeReceiver">
<intent-filter >
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
</application>
Broadcast Receiver
package com.gdm.internetconnectivitycheck;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import static android.content.Context.CONNECTIVITY_SERVICE;
public class NetworkStateChangeReceiver extends BroadcastReceiver {
public static final String NETWORK_AVAILABLE_ACTION = "com.gdm.retailalfageek.NetworkAvailable";
public static final String IS_NETWORK_AVAILABLE = "isNetworkAvailable";
#Override
public void onReceive(Context context, Intent intent) {
Intent networkStateIntent = new Intent(NETWORK_AVAILABLE_ACTION);
networkStateIntent.putExtra(IS_NETWORK_AVAILABLE, isConnectedToInternet(context));
LocalBroadcastManager.getInstance(context).sendBroadcast(networkStateIntent);
Log.e("Network Available ", "On receive called");
}
private boolean isConnectedToInternet(Context context) {
try {
if (context != null) {
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
return networkInfo != null && networkInfo.isConnected();
}
return false;
} catch (Exception e) {
Log.e(NetworkStateChangeReceiver.class.getName(), e.getMessage());
return false;
}
}
}
Main Activity
package com.gdm.internetconnectivitycheck;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import static com.gdm.internetconnectivitycheck.NetworkStateChangeReceiver.IS_NETWORK_AVAILABLE;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
IntentFilter intentFilter = new IntentFilter(NetworkStateChangeReceiver.NETWORK_AVAILABLE_ACTION);
LocalBroadcastManager.getInstance(this).registerReceiver(new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
boolean isNetworkAvailable = intent.getBooleanExtra(IS_NETWORK_AVAILABLE, false);
String networkStatus = isNetworkAvailable ? "connected" : "disconnected";
Snackbar.make(findViewById(R.id.main_activity), "Network Status: " + networkStatus, Snackbar.LENGTH_LONG).show();
}
}, intentFilter);
}
}
Apps targeting Android 7.0 (API level 24) and higher must register the
following broadcasts with
registerReceiver(BroadcastReceiver,IntentFilter)
Declaring a receiver in the manifest does not work.
CONNECTIVITY_ACTION
Beginning with Android 8.0 (API level 26), the
system imposes additional restrictions on manifest-declared receivers.
If your app targets API level 26 or higher, you cannot use the
manifest to declare a receiver for most implicit broadcasts
(broadcasts that do not target your app specifically). You can still
use a context-registered reciever when the user is actively using your
app.
directly from official doc.
you need to register for CONNECTIVITY_CHANGE action at runtime from activity.
using registerReceiver.
IntentFilter filter = new IntentFilter();
filter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
registerReceiver(new NetworkStateChangeReceiver(), filter);
And don't forget to unregister.
I am trying to build a simple app that can notify if there is a sms incoming. Just get the broadcaster to work, but what happens is that my app crashes when I get a SMS, and then next time it get a SMS nothing happens. I don't have any error message to go after or show either.
Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.studerande.upg62_b">
<uses-permission android:name="android.permission.RECEIVE_SMS"/>
<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=".IncomingSmsBroadcastReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
</application>
</manifest>
my broadcaster class which extends BroadcastReceiver. Excuse my Toasts but I just wanted to see if it was running but it isn't..
package com.example.studerande.upg62_b;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.widget.Toast;
/**
* Created by Studerande on 2017-03-18.
*/
public class IncomingSmsBroadcastReceiver extends BroadcastReceiver {
private static final String SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED";
#Override
public void onReceive(final Context context, final Intent intent) {
if (intent != null && SMS_RECEIVED.equals(intent.getAction())) {
final SmsMessage smsMessage = extractSmsMessage(intent);
processMessage(context, smsMessage);
}
Toast.makeText(context, "yo", Toast.LENGTH_SHORT).show();
}
private SmsMessage extractSmsMessage(final Intent intent) {
final Bundle pudsBundle = intent.getExtras();
final Object[] pdus = (Object[]) pudsBundle.get("pdus");
String format = pudsBundle.getString("format");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
SmsMessage smsMessage = SmsMessage.createFromPdu((byte[]) pdus[0], format);
return smsMessage;
}
else {
SmsMessage smsMessage = SmsMessage.createFromPdu((byte[]) pdus[0]);
return smsMessage;
}
}
private void processMessage(final Context context, final SmsMessage smsMessage) {
// Do something interesting here
Toast.makeText(context, "yo", Toast.LENGTH_SHORT).show();
}
}
MainActivity. You don't need to do anything here if I understood it correctly right?
package com.example.studerande.upg62_b;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
I realized that the problem is because of the API version. The broadcaster works in phone that has API 22 or below, but not in the later versions because of the new permission-handling that was introduced. So I need to ask permission before I can read SMS. https://developer.android.com/training/permissions/requesting.html
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).
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Trying to start a service on boot on Android
BroadcastReceiver
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class StartActivityAtBoot extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) {
Intent i = new Intent(context, CompareIMSI.class);
context.startService(i);
}
}
}
CompareSIM.java
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.IBinder;
import android.telephony.TelephonyManager;
import android.widget.Toast;
public class CompareIMSI extends Service{
Context context;
TelephonyManager operator;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
Toast.makeText(this, "Service Created", Toast.LENGTH_LONG).show();
//compareSIM();
}
#Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
}
#Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
compareSIM();
}
public void compareSIM(){
final String STORAGE = "Storage";
SharedPreferences unique = getSharedPreferences(STORAGE, 0);
final String storedIMSI = unique.getString("simIMSI", "");
final String currentIMSI = getSubscriberId().toString();
if (!storedIMSI.equals(currentIMSI)){
Intent i = new Intent(CompareIMSI.this, ScreenLockActivity.class);
startActivity(i);
}
}
public String getSubscriberId(){
String IMSI = null;
String serviceName = Context.TELEPHONY_SERVICE;
TelephonyManager m_telephonyManager = (TelephonyManager) getSystemService(serviceName);
IMSI = m_telephonyManager.getSubscriberId();
return IMSI;
}
}
I would like the application to start the compareSIM service upon boot up, during boot up, this service will run as the current attached SIM card IMSI will be retrieved and matched with the already saved IMSI, once they are different the user will be brought to a login layout. I want to perform this during boot up but failed to do so... Kindly advice me on the coding, thanks
floow these steps for stating your service on BOOT:
Step 1: In AndroidManifest.xml add BOOT_COMPLETED permission as:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"></uses-permission>
Step 2: In AndroidManifest.xml Register your Reciver as:
<receiver android:name=".StartActivityAtBoot" android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</receiver>
Step 3: In AndroidManifest.xml Register your Service as:
<service android:name=".CompareIMSI"> </service>
Step 3: In StartActivityAtBoot Start your service as:
public class StartActivityAtBoot extends BroadcastReceiver
{
static final String ACTION = "android.intent.action.BOOT_COMPLETED";
public void onReceive(Context context, Intent intent)
{
if (intent.getAction().equals(ACTION))
{
context.startService(new Intent(context,
CompareIMSI.class), null);
Toast.makeText(context, "CompareIMSI service has started!", Toast.LENGTH_LONG).show();
}
}
}
This is all about Starting a Service on Boot.Thanks
You need to register the BroadcastReceiver in the Android manifest, like this:
<receiver android:name=".StartActivityAtBoot">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
Also make sure that you have this permission in the manifest:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
Check Your androidManifest file. You need to add receiver at androidManifest file.
<receiver android:name=".......StartActivityAtBoot" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.category.HOME" />
</intent-filter>
</receiver>