I want to get my Device IMEI without calling onCreate method in my class:
public class EM extends OrmLiteBaseActivity<DatabaseHelper>
{
public void CreateMessage(Exception e, String className)
{
try
{
TelephonyManager manager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
String deviceid = manager.getDeviceId();
}
catch (Exception x)
{
x.printStackTrace();
}
}
}
but I keep on getting this error: "System services not available to Activities before onCreate()". Is there any way to get IMEI without calling OnCreate?
Related
the environment is Xamarin.forms in android,
but there are no Information about this.
how can i get WifiConfiguration from callback.onstarted ?
OR can i WifiManager.LocalOnlyHotspotReservation get value from callback.onstarted ?
please check below code, the code is about to using wifi AP over oreo version
when java code, i refer this article
a link
private WifiManager wifiManager;
private WifiManager.LocalOnlyHotspotReservation reservation;
void SetHotSpot()
{
wifiManager = (WifiManager)Android.App.Application.Context.GetSystemService(Context.WifiService);
WifiManager.LocalOnlyHotspotCallback callback = new WifiManager.LocalOnlyHotspotCallback();
callback.OnStarted( reservation);
wifiManager.StartLocalOnlyHotspot(callback, new Handler());
}
void getConfiguration(object sender, System.EventArgs e)
{
if (reservation != null)
{
Log.Debug("config", reservation.WifiConfiguration.Ssid);
Log.Debug("config", reservation.WifiConfiguration.NetworkId.ToString());
Log.Debug("config", reservation.WifiConfiguration.PreSharedKey);
Log.Debug("config", reservation.WifiConfiguration.Bssid);
}
}
but when i click button, reservation is null. so Log Dose not output anything.
I converted the Java code here and came up with the following solution which seems to be working kindly take a look and let me know whether or not it works for you.
Add a Callback class that inherits from WifiManager.LocalOnlyHotspotCallback and pass the Activity in my case it is the MainActivity.
public class OreoWifiManagerCallback : WifiManager.LocalOnlyHotspotCallback
{
private const string TAG = nameof(OreoWifiManagerCallback);
private MainActivity mainActivity;
public OreoWifiManager(Activity _activity)
{
if (_activity.GetType() == typeof(MainActivity))
mainActivity = (MainActivity)_activity;
}
public override void OnStarted(WifiManager.LocalOnlyHotspotReservation reservation)
{
base.OnStarted(reservation);
Log.Debug(TAG, "Wifi Hotspot is on now");
mainActivity.mReservation = reservation;
}
public override void OnFailed([GeneratedEnum] LocalOnlyHotspotCallbackErrorCode reason)
{
base.OnFailed(reason);
Log.Debug(TAG, "onStopped: ");
}
public override void OnStopped()
{
base.OnStopped();
Log.Debug(TAG, "onFailed: ");
}
}
Then add a property in the MainActivity to keep track of the reservations
public WifiManager.LocalOnlyHotspotReservation mReservation { get; set; }
And then use these methods to turn on or off wifi in that Activity, also note that you can have a global field for wifi manager if needed.
private void TurnOnHotspot()
{
var WifiManager = (WifiManager)this.Application.GetSystemService(Android.Content.Context.WifiService);
WifiManager.StartLocalOnlyHotspot(new OreoWifiManagerCallback(this), new Handler());
}
private void TurnOffHotspot()
{
if (mReservation != null)
{
mReservation.Close();
}
}
Good luck
Feel free to revert at any time
Can anybody please tell me? I am making a sample and want to detect miss call on a particular number. Suppose I opened the dialler with the number (0123456789) and when call on this number then detect missed call on this number. how can I do that. Please help ..
Check the flowing code ->
In your broadcast receiver check that if the call is received or not. Then you can find the call status.
public class CallBroadcast extends BroadcastReceiver {
private static boolean isMissedCall;
#Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
try {
if (bundle != null) {
String state = bundle.getString(TelephonyManager.EXTRA_STATE);
if (state.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
// Ringing
isMissedCall = true;
} else if (state.equals(TelephonyManager.EXTRA_STATE_OFFHOOK)) {
// Call Received
isMissedCall = false;
} else if (state.equals(TelephonyManager.EXTRA_STATE_IDLE)) {
// Call Drop
// If don't receive call then it will be missed call
if(isMissedCall){
// do your code for missed call
}
}
}
}catch (Exception e){e.printStackTrace();}
}
}
I have an android application that detect the incoming calls, i need to improve this app to work on a duos mobile device.
so i create a broadcast receiver registered in manifest for actions: phone state changed and on my onReceive method i need to check which sim receive the call. This is my code
Protected void onReceive(Context c, Intent i)
{
Int whichSim = intent
getIntExtra("simSlot",-1);
// so this methof return 0 for sim 1 and 1 for sim2
If(whichSim==-1)
WhichSim=intent.getIntExtra("com.androie.phone.extra.slot",-1);
}
I run this app on a device 4.2
2 and its working normally but when i run it on a device 4
4.4 so this method does not work, i mean that which sim return -1 in all cases. Can anyone help me?
Android does not support dual sim phone until Android 5.1 and therefore any extension to support it may be device and version specific. The following is specific for the class of phones using a variant of MultiSimTelephonyManager to handle dual sims, including Samsung duos galaxy J1 under Android 4.4.4.
Basically this class of dual sim phones use two instances of MultiSimTelephonyManager, subclassed from the regular TelephonyManager and each responsible for one SIM slot, as an interface to control the phone.
One of the means to detect the incoming call is to use the PhoneStateListener class (instead of using a receiver) to detect change in phone states. The PhoneStateListener in these phones are modified (rather than subclassed) to include a mSubscription field which should indicate the SIM slot of the listener.
Both the MultiSimTelephonyManager class and the mSubscription field of PhoneStateListener are not in the standard SDK. To compile the app to use these interface, Java Reflection is needed.
The following code should roughly illustrate how you could get the sim slot information from incoming calls. I do not have the device to test, so the code may need refinements.
Set up the listener during your initialization stage -
try {
final Class<?> tmClass = Class.forName("android.telephony.MultiSimTelephonyManager");
// MultiSimTelephonyManager Class found
// getDefault() gets the manager instances for specific slots
Method methodDefault = tmClass.getDeclaredMethod("getDefault", int.class);
methodDefault.setAccessible(true);
try {
for (int slot = 0; slot < 2; slot++) {
MultiSimTelephonyManager telephonyManagerMultiSim = (MultiSimTelephonyManager)methodDefault.invoke(null, slot);
telephonyManagerMultiSim.listen(new MultiSimListener(slot), PhoneStateListener.LISTEN_CALL_STATE);
}
} catch (ArrayIndexOutOfBoundsException e) {
// (Not tested) the getDefault method might cause the exception if there is only 1 slot
}
} catch (ClassNotFoundException e) {
//
} catch (NoSuchMethodException e) {
//
} catch (IllegalAccessException e) {
//
} catch (InvocationTargetException e) {
//
} catch (ClassCastException e) {
//
}
Override PhoneStateListener and set the mSubscription field to listen to phone state changes:
public class MultiSimListener extends PhoneStateListener {
private Field subscriptionField;
private int simSlot = -1;
public MultiSimListener (int simSlot) {
super();
try {
// Get the protected field mSubscription of PhoneStateListener and set it
subscriptionField = this.getClass().getSuperclass().getDeclaredField("mSubscription");
subscriptionField.setAccessible(true);
subscriptionField.set(this, simSlot);
this.simSlot = simSlot;
} catch (NoSuchFieldException e) {
} catch (IllegalAccessException e) {
} catch (IllegalArgumentException e) {
}
}
#Override
public void onCallStateChanged(int state, String incomingNumber) {
// Handle the event here, with state, incomingNumber and simSlot
}
}
You will also need to create a file named MultiSimTelephonyManager.java at the [project]/src/android/telephony directory.
package android.telephony;
public interface MultiSimTelephonyManager {
public void listen(PhoneStateListener listener,int events);
}
You should probably do some error checking and especially check if the phone is the target model, when using the code.
Please be warned (again) that the above would not work in most other phones and other Android versions of the same phone.
This question suggests "com.android.phone.extra.slot" may also work on some phones. Maybe try both and use the one that didn't return -1?
Have you Try this Method :-
in this method you will get 0 for 1 Sim and for second sim you will get 1.
//Working code For 4.4 Phones KitKat
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
whichSIM = intent.getExtras().getInt("subscription");
if (whichSIM == 0) {
whichSIM = 1;
editor.putLong("ChooseSim", whichSIM);
editor.commit();
// Incoming call for SIM1
} else if (whichSIM == 1) {
whichSIM = 2;
editor.putLong("ChooseSim", whichSIM);
editor.commit();
}
I would like to know the purpose of foloowing two files:
frameworks/base/core/java/android/app/IActivityWatcher.aidl
[description: Callback interface to watch the user's traversal through activities.]
frameworks/base/core/java/android/app/IProcessObserver.aidl
[no description]
I am trying to build an app wherein user can decide which apps can be run during particular period of time (say, from 10am till 4pm).
Is there any way where my app will get notified if one the apps specified by the user starts? This way my app can send kill command (I am assuming that root access is available.)
It seems that IActivityWatcher has been removed beginning with JellyBean, in order to monitor which Activity is running foreground, you can use IProcessObserver as following:
mActivityManagerNative = ActivityManagerNative.getDefault();
if (mActivityManagerNative != null) {
try {
mActivityManagerNative.registerProcessObserver(mProcessObserver);
} catch (RemoteException e) {
Log.e("TAG", "onCreate() RemoteException!");
}
}
private IProcessObserver.Stub mProcessObserver = new IProcessObserver.Stub() {
#Override
public void onForegroundActivitiesChanged(int pid, int uid, boolean foregroundActivities) {
doWhatUWantHere();
}
#Override
public void onImportanceChanged(int pid, int uid, int importance) {
}
#Override
public void onProcessDied(int pid, int uid) {
}
};
P.S.
You can use following code snippets to get the package name of foreground running Activity:
private String getForegroundPackage() {
ActivityManager am = (ActivityManager)getSystemService(Context.ACTIVITY_SERVICE);
List<RecentTaskInfo> taskInfo = am.getRecentTasks(1,
ActivityManager.RECENT_IGNORE_UNAVAILABLE);
return taskInfo.isEmpty()
? null : taskInfo.get(0).baseIntent.getComponent().getPackageName();
}
In one of my app i wanted to check the service state of the android phone
before sending sms. I have used the following code to do that
//check service
ServiceState pstate = new ServiceState();
if(pstate.getState() != ServiceState.STATE_IN_SERVICE)
{
Log.v(TAG,"service state" +pstate.getState());
Toast.makeText(Myactivity.this, "error string", 2000).show();
return;
}
But the code always returns with OUT_OF_SERVICE ( value of 1 in +pstate.getState)
Please let me know what is the reliable way to check whether the phone is in STATE_IN_SERVICE or not?
This code was checked in FROYO version.
Not a satisfactory answer really, but I've had he same problem and kept wasting time, but it would just not work on my FROYO version aswell.
But using the TelephonyManager and PhoneStateListener this worked perfectly fine. For your case I'd suggest using a wrapper instead of instantiating the ServiceState directly, ie
//declare current state
ServiceState myServiceState = new ServiceState();
PhoneStateListener listener = null; // not sure if this is needed really..
// nifty getter
public ServiceState getServiceState(){ return myServiceState; }
//setup listener (eg. in onCreate)
TelephonyManager tm = (TelephonyManager) context.getSystemService(context.TELEPHONY_SERVICE);
listener = new PhoneStateListener() {
#Override
public void onServiceStateChanged(ServiceState serviceState){
myServiceState = serviceState;
}
};
tm.listen(listener,PhoneStateListener.LISTEN_SERVICE_STATE);
// to be called when destroying your context
public void unregisterListener(){
// something like..
tm.listen(listener,PhoneStateListener.LISTEN_NONE);
}
//check service
ServiceState pstate = getServiceState();
if(pstate.getState() != ServiceState.STATE_IN_SERVICE)
{
Log.v(TAG,"service state" +pstate.getState());
Toast.makeText(Myactivity.this, "error string", 2000).show();
return;
}
A lazier solution would be moving the listener-setup into the getter and registering it only when actually called, if ever, and only saving if the service is available. ie
//declaration
boolean isAvailable = false;
PhoneStateListener listener = null;
// more nifty getter
public boolean isServiceAvailable(){
if (listener == null){
//setup listener if not yet done
TelephonyManager tm = (TelephonyManager) context.getSystemService(context.TELEPHONY_SERVICE);
listener = new PhoneStateListener() {
#Override
public void onServiceStateChanged(ServiceState serviceState){
isAvailable = serviceState.getState() == ServiceState.STATE_IN_SERVICE;
}
};
tm.listen(listener,PhoneStateListener.LISTEN_SERVICE_STATE);
}
return isAvailable;
}
// to be called when destroying your context
public void unregisterListener(){
// something like..
if (lister != null){
tm.listen(listener,PhoneStateListener.LISTEN_NONE);
}
}
//check service
if(! isServiceAvailable())
{
Log.v(TAG,"service state" +pstate.getState());
Toast.makeText(Myactivity.this, "error string", 2000).show();
return;
}
But be aware, that would require the listener to get called immediately upon registration, otherwise you'll end up with arbitrary results - so make sure to check that.