BroadcastReceiver for shutdown is not triggering on programmatically rebooting the device - android

I have to reboot the device on specific time.i am using below code for that
private void rebootAfterSomeTime() {
h = new Handler(Looper.getMainLooper());
r = new Runnable() {
public void run() {
//current time
Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR_OF_DAY);
int min = c.get(Calendar.MINUTE);
int sec = c.get(Calendar.SECOND);
String currenttime = String.valueOf(hour) + " : " + String.valueOf(min) + " : " + String.valueOf(sec);
Log.d("Gajanand", "run: "+currenttime);
//comparing current time with 12:00pm
if (currenttime.equals("23 : 59 : 59")) {
//reboot the device
rebootDevice();
}
h.postDelayed(this, delayMillis);
}
};
h.post(r);
}
i am rebooting the device with two methods one by using powerManager and another by using SU..like below
private void systemAppsrebootOnly() {
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
pm.reboot(null);
}
public static void rebootDevice() {
try {
Process process = Runtime.getRuntime().exec("su");
DataOutputStream os = new DataOutputStream(process.getOutputStream());
os.writeBytes("reboot \n");
} catch (Throwable t) {
t.printStackTrace();
}
}
Yes in both the cases device is rebooting properly.but the BroadcastReceiver is not triggering in both the case. but when i reboot device manually by long pressing power button and reboot that time BroadcastReceiver is triggering. here is my ShutdownReceiver
public class ShutdownReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
/*if(intent.getAction().equalsIgnoreCase("android.intent.action.BOOT_COMPLETED"))
{
Toast.makeText(context, "boot_completed", Toast.LENGTH_SHORT).show();
}
else*/
// Toast.makeText(context, ""+intent.getAction(), Toast.LENGTH_SHORT).show();
Log.e("kishan", "onReceive:mPowerReceiver powerofffffffffff");
ManvishPrefConstants.SHUTDOWN_TRIGGERED.write(true);
ManvishPrefConstants.SHUTDOWN_DATE_TIME.write(CommanUtils.formatDate(System.currentTimeMillis()));
}
}
Small part of my manifest file.i have added all necessary permissions.
<receiver android:name=".Activities.ShutdownReceiver">
<intent-filter>
<action android:name="android.intent.action.ACTION_SHUTDOWN"/>
<action android:name="android.intent.action.ACTION_REBOOT"/>
<action android:name="android.intent.action.QUICKBOOT_POWEROFF"/>
</intent-filter>
</receiver>
any help ?

Related

How Call the getDataFromApi() function using Thread

I'm taking the google calendar API data for my mobile application. i want to check the time to time the changes of the calendar. For that i know, i have to used a thread.
if (isChecked) {
Runnable runnable = new Runnable() {
public void run() {
long endTime = System.currentTimeMillis() + 1000;
while (System.currentTimeMillis() < endTime) {
synchronized (this) {
try {
getResultsFromApi();
} catch (Exception e) {}
}
}
}
};
Thread mythread = new Thread(runnable);
mythread.start();
Toast.makeText(AlertActivity.this, "Calendar Settings Enabled",
Toast.LENGTH_SHORT).show();
} else {
// The toggle is disabled
for(int i=0;i<=broadcastCodeCal;i++)
cancel_Alarm(i);
Toast.makeText(AlertActivity.this, "Calendar Settings Disabled",
Toast.LENGTH_SHORT).show();
}
I want to know how to check the calendar details changes time time to through the mobile application... please guide me...
Create a JobScheduler as below
public static void scheduleJob(Context context) {
ComponentName serviceComponent = new ComponentName(context, TestJobService.class);
JobInfo.Builder builder = new JobInfo.Builder(0, serviceComponent);
builder.setMinimumLatency(1 * 1000); // wait at least
builder.setOverrideDeadline(3 * 1000); // maximum delay
JobScheduler jobScheduler = context.getSystemService(JobScheduler.class);
jobScheduler.schedule(builder.build());
}
Create the following receiver
public class MyStartServiceReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Util.scheduleJob(context);
}
}
Register the receiver in the Android manifest for the BOOT_COMPLETED event.
<receiver android:name="MyStartServiceReceiver" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
Create a JobService and add your existing code in to onStartJob
public class TestJobService extends JobService {
private static final String TAG = "SyncService";
#Override
public boolean onStartJob(JobParameters params) {
Intent service = new Intent(getApplicationContext(), LocalWordService.class);
getApplicationContext().startService(service);
Util.scheduleJob(getApplicationContext()); // reschedule the job
return true;
}
#Override
public boolean onStopJob(JobParameters params) {
return true;
}
}
For more details refer : linkhere

Broadcast receiver not working in android oreo

My Broadcast receiver is not working on oreo but its working below oreo it's working fine, I searched a lot regarding this but could not find the suitable solution. Does anyone face the same problem, here is my code regarding my service in which broadcast has been implemented. Kindly suggests me that how I can make in working in oreo.
Here is the class
public int onStartCommand(Intent intent, int flags, int startId) {
mContext = this;
mAppPreferences = new AppPreferences(mContext);
if (intent.getExtras() != null) {
data = (String) intent.getExtras().get("showPopUp");
phoneNumber= (String) intent.getExtras().get("dialNumber");
}
final IntentFilter intentFilter = new IntentFilter();
if (data.equalsIgnoreCase("true")) {
showPopup(getApplicationContext());
Utils.ApiHit(phoneNumber,getApplicationContext());
}
intentFilter.setPriority(2147483647);
intentFilter.addAction("android.intent.action.PHONE_STATE");
callExplicitReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(TelephonyManager.ACTION_PHONE_STATE_CHANGED)) {
if (intent.getAction().equals("android.intent.action.NEW_OUTGOING_CALL")) {
savedNumber = intent.getExtras().getString("android.intent.extra.PHONE_NUMBER");
} else {
String stateStr = intent.getExtras().getString(TelephonyManager.EXTRA_STATE);
phoneNumber = 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;
}
onCallStateChanged(context, state, phoneNumber);
}
}
}
};
mContext.registerReceiver(callExplicitReceiver, intentFilter);
return START_NOT_STICKY;
}
public void onIncomingCallReceived(Context ctx, String number, Date start) {
}
public void onIncomingCallAnswered(Context ctx, String number, Date start) {
if (popupView.getVisibility() == View.GONE) {
popupView.setVisibility(View.VISIBLE);
}
}
public void onIncomingCallEnded(Context ctx, String number, Date start, Date end) {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
DeleteCallLogByNumber(number);
}
}, 2000);
if (popupView.getVisibility() == View.VISIBLE) {
popupView.setVisibility(View.GONE);
}
}
public void onOutgoingCallStarted(Context ctx, String number, Date start) {
// mAppPreferences.setPrefrenceString("busy", "yes");
// if (data.equalsIgnoreCase("true")) {
mediaPlayer = MediaPlayer.create(ctx, R.raw.speech_audio);
// } else {
// mediaPlayer = MediaPlayer.create(ctx, R.raw.speech_audio);
// }
mediaPlayer.start();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
if (mediaPlayer != null && mediaPlayer.isPlaying()) {
mediaPlayer.stop();
mediaPlayer.release();
}
}
}, 12000);
if (popupView.getVisibility() == View.GONE) {
popupView.setVisibility(View.VISIBLE);
}
}
public void onOutgoingCallEnded(Context ctx, String number, Date start, Date end) {
mAppPreferences.setPrefrenceString("busy", "no");
if (mediaPlayer != null && mediaPlayer.isPlaying()) {
mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer = null;
}
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
DeleteCallLogByNumber(phoneNumber);
}
}, 2000);
if (popupView.getVisibility() == View.VISIBLE) {
popupView.setVisibility(View.GONE);
}
}
public void onMissedCall(Context ctx, String number, Date start) {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
DeleteCallLogByNumber(phoneNumber);
}
}, 2000);
if (popupView.getVisibility() == View.VISIBLE) {
popupView.setVisibility(View.GONE);
}
}
public void onCallStateChanged(Context context, int state, String number) {
if (lastState == state) {
return;
}
switch (state) {
case TelephonyManager.CALL_STATE_RINGING:
isIncoming = true;
callStartTime = new Date();
savedNumber = number;
onIncomingCallReceived(context, number, callStartTime);
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
if (lastState != TelephonyManager.CALL_STATE_RINGING) {
isIncoming = false;
callStartTime = new Date();
onOutgoingCallStarted(context, savedNumber, callStartTime);
} else {
isIncoming = true;
callStartTime = new Date();
onIncomingCallAnswered(context, savedNumber, callStartTime);
}
break;
case TelephonyManager.CALL_STATE_IDLE:
if (popupView.getVisibility() == View.VISIBLE) {
popupView.setVisibility(View.GONE);
}
if (lastState == TelephonyManager.CALL_STATE_RINGING) {
onMissedCall(context, savedNumber, callStartTime);
} else if (isIncoming) {
onIncomingCallEnded(context, savedNumber, callStartTime, new Date());
} else {
onOutgoingCallEnded(context, savedNumber, callStartTime, new Date());
}
break;
}
lastState = state;
}
#Override
public void onDestroy() {
mContext.unregisterReceiver(callExplicitReceiver);
}
Noting is in coming inside receiever,Can anyone help me out in this?
New Additions as per discussion
Manifest data :-
Permission used :-
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
Reciver:-
<receiver android:name="com.example.dialer.AppUtils.StartUpBootReceiver" android:enabled="true" android:exported="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
My BroadCast Reciever Class :-
public class StartUpBootReceiver extends BroadcastReceiver {
private Context mContext;
#Override
public void onReceive(Context context, Intent intent) {
mContext= context;
String action = "START";
if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
{
context.startForegroundService(new Intent(context, PhoneStateService.class));
}
else
{
context.startService(new Intent(context, PhoneStateService.class));
}
}
}
private boolean isServiceRunning(Class<?> serviceClass) {
ActivityManager manager = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
}
Rest the same service will get the call, but the problem is i still does not get call in receiver.And m primary point is that service should only get called once user tap on button , not automatically as i have to pass some values in the service.
Thanks
Broadcast Limitations
If an app registers to receive broadcasts, the app's receiver consumes resources every time the broadcast is sent. This can cause problems if too many apps register to receive broadcasts based on system events; a system event that triggers a broadcast can cause all of those apps to consume resources in rapid succession, impairing the user experience. To mitigate this problem, Android 7.0 (API level 25) placed limitations on broadcasts, as described in Background Optimization. Android 8.0 (API level 26) makes these limitations more stringent.
Apps that target Android 8.0 or higher can no longer register broadcast receivers for implicit broadcasts in their manifest. An implicit broadcast is a broadcast that does not target that app specifically. For example, ACTION_PACKAGE_REPLACED is an implicit broadcast, since it is sent to all registered listeners, letting them know that some package on the device was replaced. However, ACTION_MY_PACKAGE_REPLACED is not an implicit broadcast, since it is sent only to the app whose package was replaced, no matter how many other apps have registered listeners for that broadcast.
Apps can continue to register for explicit broadcasts in their manifests.
Apps can use Context.registerReceiver() at runtime to register a receiver for any broadcast, whether implicit or explicit.
Broadcasts that require a signature permission are exempted from this restriction, since these broadcasts are only sent to apps that are signed with the same certificate, not to all the apps on the device.
From the Official Documentation
The problem comes with the service you're trying to run, services or persistent background services are not permitted to run for long for apps targeting Oreo and above.
Check this guide and this as well for migrating your app to support Oreo.
I also had this kind of issue, but I found a better solution:
Class MyReceiver
#BroadcastReceiverActions({
"android.intent.action.SCREEN_ON",
"android.intent.action.SCREEN_OFF",
"android.intent.action.DREAMING_STARTED",
"android.intent.action.DREAMING_STOPPED",
"android.intent.action.ACTION_POWER_DISCONNECTED",
"android.intent.action.ACTION_POWER_CONNECTED",
"android.net.conn.CONNECTIVITY_CHANGE"
})
public class MyReceiver extends BroadcastReceiver {
public MyReceiver() {
super();
}
#Override
public void onReceive(Context context, Intent intent) {
Session.getGlobalReceiverCallBack(context, intent);
//Log.e("dfd", "" + intent.getAction());
}
}
Class AppController
public class AppController extends Application {
private BroadcastReceiver receiver;
MyReceiver mR;
#Override
public void onCreate() {
super.onCreate();
mR = new MyReceiver();
receiver = DynamicReceiver.with(mR)
.register(this);
}
}
Class MainActivity
public class MainActivity extends AppCompatActivity implements GlobalReceiverCallBack {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Session.setmGlobalReceiverCallback(this);
}
#Override
public void onCallBackReceived(Context context, Intent intent) {
Toast.makeText(context, "" + intent.getAction(), Toast.LENGTH_LONG).show();
}
}
For complete reference you can see also https://github.com/devggaurav/BroadcastReceiver-For-Naught-and-Oreo-devices
Register your broadcast receiver in activity on create method rather than in manifest and unregister it on destroy method. Hope this will work on android 9.
Android 8.0 offers several improvements to JobScheduler that make it easier to replace services and broadcast receivers with scheduled jobs:
https://developer.android.com/about/versions/oreo/background
In many cases, apps that previously registered for an implicit broadcast can get similar functionality by using a JobScheduler job. For example, a social photo app might need to perform cleanup on its data from time to time, and prefer to do this when the device is connected to a charger. Previously, the app registered a receiver for ACTION_POWER_CONNECTED in its manifest; when the app received that broadcast, it would check whether cleanup was necessary. To migrate to Android 8.0 or higher, the app removes that receiver from its manifest. Instead, the app schedules a cleanup job that runs when the device is idle and charging.
I have faced the similar issue when implementing call recording app,
I have added the following code in the AndroidManifest.xml file, then the register is working normally
<receiver android:name=".Services.Receiver"
android:permission="android.permission.RECEIVE_BOOT_COMPLETED"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE"/>
<action android:name="android.intent.action.ANSWER"/>
<action android:name="android.intent.action.CALL_BUTTON"/>
<action android:name= "android.intent.action.NEW_OUTGOING_CALL"/>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>

Setting a timeout and finishing an ActivityforResult activity

I'd like to know if there's some way to set a timeout for an Intent started via startActivityForResult, so when the time is passed some actions can be performed with the activity of the mentioned intent (in my case finishing it).
There doesn't seem to be any direct way to set a timeout directly to the Intent, but this doesn't look too much to worry about, as I guess I could create a CountDownTimer that in onFinish() would call the code to finish the intent.
Problem is I don't see a way to finish that ActivityForResult.
Is there any way to do this?
Well, I finally got to solve the problem, indeed it wasn't very difficult.
For my particular case of INTENT_PICK the following code is valid to stop the activity after 2 minutes:
final int RQS_PICKCONTACT = 1;
[...]
Intent intentPickContact = new Intent(Intent.ACTION_PICK, uriContact);
startActivityForResult(intentPickContact, RQS_PICKCONTACT);
mcd = new CountDownTimer(120000, 10000) {
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
try
{
finishActivity(RQS_PICKCONTACT);
}
catch (Exception ex)
{
}
}
}.start();
In my case I wanted to limit the time a user was doing a task so I created my own timer class.
public class Timer {
private static final String TAG = "Timer" ;
int timeout;
Context mContext;
boolean compleatedTask;
String timeoutKey;
CountDownTimer countDown;
public Timer(Context mContext, int timeout, String timeoutKey){
this.timeout = timeout;
this.mContext = mContext;
this.timeoutKey = timeoutKey;
}
public void startTimer() {
this.countDown = new CountDownTimer(this.timeout, 1000) {
public void onTick(long millisUntilFinished) {
Log.i(TAG, "OnTick, context: " + mContext + ", milisUntilFinished: " + millisUntilFinished + ", compleatedTask: " + compleatedTask);
if(compleatedTask)
cancel();
}
public void onFinish() {
Log.i(TAG, "OnFinish, context: " + mContext + ", compleatedTask: " + compleatedTask);
try
{
if(!compleatedTask){
Intent intent = new Intent(mContext, UnsuccessfullPosTaskActivity.class);
intent.putExtra("error", StateMachine.databaseAccess.getDictionaryTranslation(timeoutKey, StateMachine.language));
mContext.startActivity(intent);
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
};
countDown.start();
}
public void setCompleatedTask(boolean compleatedTask){
this.compleatedTask = compleatedTask;
if(compleatedTask)
countDown.onFinish();
}
}
Then in your activity
int timeout = 1000;
Timer timer = new Timer(Activity.this, timeout);
timer.startTimer();
//do stuff
if(conditionToStop)
timer.setCompleatedTask(true);
And if you are using recycle views and you want to stop the counter when they click an option just send the timer object to your custom recycle view adapter.

How to get MIUI Security app auto start permission programmatically?

I am not getting BOOT_COMPLETE broadcast in my Xiaomi Redmi 2 Prime mobile.
My BroadcastReciever is ---
public class OnBootReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// Setting singleAlarm
SingleAlarmHandler.getInstance().setAlarm(context);
try {
// Sending System Setting broadcast
String offDate = SharedPrefrencesHandler.getInstance(context).readString(SharedPrefrencesConstants.SWITCH_OFF_DATE);
int type = SystemSettingsType.PHONE_SWITCH_ON_OFF.getNumericType();
if (offDate == null)
offDate = "";
SystemSettingsHandler.getSystemSettingsHandler().makeSystemSettingsCall(context, type, offDate);
SharedPrefrencesHandler.getInstance(context).removePrefrence(SharedPrefrencesConstants.SWITCH_OFF_DATE);
} catch (Exception e) {
Log.e(ChaseForceApplication.TAG, e.getMessage());
}
}
}
and manifest:
<receiver
android:name=".broadcastlisteners.OnBootReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
with permission:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
Now I am not getting BOOT COMPLETE broadcast in my Xiaomi Redmi 2 Prime mobile as alarm is not set. But in other android mobiles it is working correctly.
I searched and found that it is problem in MIUI firmware. In such mobile they provide an in built security app and until you allow auto start permission in that Security app, you are unable to get broad cast (any notification).
And as soon as you check that permission in that app you start to get the broadcast.
Now my question is:
How to get MIUI Security app auto start permission( Phones like Redmi) programmatically?
this question already has answer in two Stack Overflow threads:
thread #1 https://stackoverflow.com/a/40932178/1537413
String xiaomi = "Xiaomi";
final String CALC_PACKAGE_NAME = "com.miui.securitycenter";
final String CALC_PACKAGE_ACITIVITY = "com.miui.permcenter.autostart.AutoStartManagementActivity";
if (deviceManufacturer.equalsIgnoreCase(xiaomi)) {
DisplayUtils.showDialog(activity, "Ask for permission", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
try {
Intent intent = new Intent();
intent.setComponent(new ComponentName(CALC_PACKAGE_NAME, CALC_PACKAGE_ACITIVITY));
activity.startActivity(intent);
} catch (ActivityNotFoundException e) {
Logger.e(TAG, "Failed to launch AutoStart Screen ", e);
} catch (Exception e) {
Logger.e(TAG, "Failed to launch AutoStart Screen ", e);
}
}
}, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
}
thread #2 https://stackoverflow.com/a/41696993/1537413
String manufacturer = "xiaomi";
if(manufacturer.equalsIgnoreCase(android.os.Build.MANUFACTURER)) {
//this will open auto start screen where user can enable permission for your app
Intent intent = new Intent();
intent.setComponent(new ComponentName("com.miui.securitycenter", "com.miui.permcenter.autostart.AutoStartManagementActivity"));
startActivity(intent);
}
and for similar problem on huawei devices:
https://stackoverflow.com/a/35220476/1537413
private void ifHuaweiAlert() {
final SharedPreferences settings = getSharedPreferences("ProtectedApps", MODE_PRIVATE);
final String saveIfSkip = "skipProtectedAppsMessage";
boolean skipMessage = settings.getBoolean(saveIfSkip, false);
if (!skipMessage) {
final SharedPreferences.Editor editor = settings.edit();
Intent intent = new Intent();
intent.setClassName("com.huawei.systemmanager", "com.huawei.systemmanager.optimize.process.ProtectActivity");
if (isCallable(intent)) {
final AppCompatCheckBox dontShowAgain = new AppCompatCheckBox(this);
dontShowAgain.setText("Do not show again");
dontShowAgain.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
editor.putBoolean(saveIfSkip, isChecked);
editor.apply();
}
});
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Huawei Protected Apps")
.setMessage(String.format("%s requires to be enabled in 'Protected Apps' to function properly.%n", getString(R.string.app_name)))
.setView(dontShowAgain)
.setPositiveButton("Protected Apps", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
huaweiProtectedApps();
}
})
.setNegativeButton(android.R.string.cancel, null)
.show();
} else {
editor.putBoolean(saveIfSkip, true);
editor.apply();
}
}
}
private boolean isCallable(Intent intent) {
List<ResolveInfo> list = getPackageManager().queryIntentActivities(intent,
PackageManager.MATCH_DEFAULT_ONLY);
return list.size() > 0;
}
private void huaweiProtectedApps() {
try {
String cmd = "am start -n com.huawei.systemmanager/.optimize.process.ProtectActivity";
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
cmd += " --user " + getUserSerial();
}
Runtime.getRuntime().exec(cmd);
} catch (IOException ignored) {
}
}
private String getUserSerial() {
//noinspection ResourceType
Object userManager = getSystemService("user");
if (null == userManager) return "";
try {
Method myUserHandleMethod = android.os.Process.class.getMethod("myUserHandle", (Class<?>[]) null);
Object myUserHandle = myUserHandleMethod.invoke(android.os.Process.class, (Object[]) null);
Method getSerialNumberForUser = userManager.getClass().getMethod("getSerialNumberForUser", myUserHandle.getClass());
Long userSerial = (Long) getSerialNumberForUser.invoke(userManager, myUserHandle);
if (userSerial != null) {
return String.valueOf(userSerial);
} else {
return "";
}
} catch (NoSuchMethodException | IllegalArgumentException | InvocationTargetException | IllegalAccessException ignored) {
}
return "";
}
You need to give permissions in the in build security application for xiaomi.
1. open the security app
2. go to permissions
3. go to auto start
4. enable the applications that you want to keep running in the background!
This worked for me..!

Sim Tracking in android

I am doing a app on sim tracking but unable to get result
here is the main activity
public class MainActivity extends Activity {
String FILENAME = "old_file.txt";
int simstatus;
String simNo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TelephonyManager tManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
if (simstatus != TelephonyManager.SIM_STATE_ABSENT) {
System.out.println("--------SIM Present:" + simstatus);
simNo = tManager.getSimSerialNumber();
FileOutputStream fos;
try {
fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(simNo.getBytes());
System.out.println("---------Data written to files is:"
+ simNo);
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
Reciever
public class SimDataReciever extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) {
System.out.println("Reciever Started");
Intent CompareSimServiceIntent = new Intent(context,demo.class);
context.startService(CompareSimServiceIntent);
}
}
}
and the service..
String FILENAME = "old_file.txt";
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
public int onStartCommand(Intent intent, int flags, final int startId) {
Timer timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
//run your service
// Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
TelephonyManager tManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
try {
FileInputStream fis = openFileInput(FILENAME);
InputStreamReader in = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(in);
String data = br.readLine();
System.out.println("---Data Read From File is:" + data);
String newsiminfo = tManager.getSimSerialNumber();
System.out.println("---New SIM no is:" + newsiminfo);
if (data.equals(tManager.getSimSerialNumber())) {
System.out.println("------Old sim Present:");
// Toast.makeText(this, "Old SIM", Toast.LENGTH_LONG).show();
} else {
// Toast.makeText(this, "New SIM", Toast.LENGTH_LONG).show();
SmsManager smsMngr = SmsManager.getDefault();
String destinationaddress = "8281306132";
String scAddress = null;
String text = "New Sim Is Inserted In Your Device";
PendingIntent sentIntent = null;
PendingIntent deliveryIntent = null;
smsMngr.sendTextMessage(destinationaddress, scAddress, text,
sentIntent, deliveryIntent);
System.out.println("-----SMS Send");
}
} catch (Exception e) {
}
}
}, 1*60*1000);
return startId;
}
}
pls help me to find the solution....
I have found similar kind of problem, when working on same kind of project.
I was also not able to track the sim after the device reboot. The problem I found here was that I was invoking the sim tracking immediately after the device reboot. But the system takes 15 to 20 seconds to load resources. The sim was not getting launched immendiately after the device reboot, so my receiver was unable to track the sim.
So, I delayed the sim tracking for 20 seconds after the device reboot. Try to delay the sim tracking and check if it works.
Edit-
Your Receiver should be like this,
public class SimDataReciever extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
System.out.println("Reciever Started");
Log.d("BOOT COMPLETE","Receiver Called");
Intent CompareSimServiceIntent = new Intent(context,demo.class);
context.startService(CompareSimServiceIntent);
}
}
and in Manifest file, replace your code with this,
<receiver android:name=".SimDataReciever"
android:enabled="true"
android:exported="false">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</receiver>
Now, check whether the messages are shown in the logcat or not.

Categories

Resources