How obtain calling event from my app Android? - java

I want to capture incoming and outgoing calls from my App, that is, while it is running, if a phone call is made or comes in that can be captured, I have implemented the BroadcastReceiver class and the PhoneStateListener class, but it is not capturing it, or perhaps the way to invoke her. I have added the permissions in the Manifest, I also invoke the Receiver with the name of the BroadcastReceiver class called "Ena_Llamadas_Manager"
This is the class below:
#SuppressLint("SimpleDateFormat") public class Ena_Llamadas_Manager extends BroadcastReceiver {
private static Context contexto;
#Override
public void onReceive(Context context, Intent intent) {
Bundle extras = intent.getExtras();
if(extras != null){
call(context,extras);
}
if ( extras.getString("state").equals(TelephonyManager.EXTRA_STATE_RINGING)) {
//codigo
}
}
public static void call(Context context, Bundle extras) {
PhoneCallListener phoneListener = new PhoneCallListener();
TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
telephonyManager.listen(phoneListener, PhoneStateListener.LISTEN_CALL_STATE);
contexto = context;
//String phoneNumber = extras.getString("incoming_number");
}
private static class PhoneCallListener extends PhoneStateListener {
public boolean isPhoneCalling = false;
Boolean wasRinging = false;
#Override
public void onCallStateChanged(int state, String incomingNumber) {
//Bundle extras = intent.getExtras();
if (TelephonyManager.CALL_STATE_RINGING == state) {
// phone ringing
//Aquí ya detectas que el teléfono esta recibiendo una llamada entrante
}
if (TelephonyManager.CALL_STATE_OFFHOOK == state) {
// active
isPhoneCalling = true;
AlertDialog.Builder builder = new AlertDialog.Builder(contexto);
builder.setMessage("Llamada saliente...")
.setCancelable(false)
.setPositiveButton("Si", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
if (TelephonyManager.CALL_STATE_IDLE == state) {
isPhoneCalling = false;
}
}
}
}
And this is the Manifest permisson:
<receiver android:name="etapa.webServices.inec.go.cr.Ena_Llamadas_Manager" >
<intent-filter
android:priority="1">
<action android:name="android.intent.action.NEW_OUTGOING_CALL"/>
<action android:name="android.intent.action.PHONE_STATE"/>
</intent-filter>
</receiver>
Finally this is the way tha invoke the class from the Main Activity
Ena_Llamadas_Manager.call(LoginActivity.this, getIntent().getExtras());

Related

Android Bound Service For Each Item of a ListView or RecyclerView

I design a List view like bellow. I learning android and I got a assinment.
---------------------------------------
File Name 1 0% Download Button
---------------------------------------
File Name 2 0% Download Button
---------------------------------------
File Name 3 0% Download Button
---------------------------------------
I have a program that use bound service and a counter in it that count 1% to 100% after clicking a button.
Now how I can use this program for each item of list view.
NOTE: I want to use bound service for this.
Bellow program have a start service button that start a bound service and send brodcast to ui to show 1% to 100% progress. I have to do it for each item in my listview or recyclerview.
In my above layout when I click download button it should start bound service and show the progress.
activity_main.xml
<Button
android:id="#+id/button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="start_service"
android:text="Start" />
<TextView
android:id="#+id/showCount"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="TextView" />
MainActivity.java
public class MainActivity extends AppCompatActivity {
TextView showCount;
private static final String TAG = "MainActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
showCount = findViewById(R.id.showCount);
Intent intent = new Intent(MainActivity.this, MyService.class);
bindService(intent, sConnection, BIND_AUTO_CREATE);
}
BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String s1 = intent.getStringExtra("DATAPASSED");
showCount.setText(s1);
}
};
public void start_service(View view) {
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(MyService.MY_ACTION);
registerReceiver(broadcastReceiver, intentFilter);
myService.startCounting();
super.onStart();
}
#Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
#Override
protected void onStop() {
super.onStop();
if (isBind) {
unbindService(sConnection);
isBind = false;
Log.d(TAG, "onStop: ");
}
}
MyService myService;
boolean isBind = false;
public ServiceConnection sConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
MyService.LocalBinder binder = (MyService.LocalBinder) iBinder;
myService = binder.getService();
isBind = true;
}
#Override
public void onServiceDisconnected(ComponentName componentName) {
isBind = false;
}
};
}
MyService.java
public class MyService extends Service {
private static final String TAG = "MyService";
static final String MY_ACTION = "MY_ACTION";
public static final String CHANNEL_ID = "CHANNEL_ID";
public final IBinder binder = new LocalBinder();
public class LocalBinder extends Binder {
MyService getService() {
return MyService.this;
}
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
Log.d(TAG, "onBind: start gn");
return binder;
}
#Override
public void onCreate() {
Log.d(TAG, "onCreate: ");
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
String input = "Supper Text";
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this,0, notificationIntent, 0);
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("Notification Title")
.setContentText(input)
.setSmallIcon(R.drawable.notification_icon)
.setContentIntent(pendingIntent)
.build();
startForeground(0, notification);
return START_NOT_STICKY;
}
#Override
public void onDestroy() {
Log.d(TAG, "onDestroy: ");
super.onDestroy();
}
#Override
public boolean onUnbind(Intent intent) {
Log.d(TAG, "onUnbind: ");
return super.onUnbind(intent);
}
#Override
public void onRebind(Intent intent) {
Log.d(TAG, "onRebind: ");
super.onRebind(intent);
}
public void startCounting() {
if (!running) {
running = true;
new GenerateNumber().start();
}
}
public void stopCounting() {
if (running) {
running = false;
}
}
int generatedNumber;
boolean running;
class GenerateNumber extends Thread {
GenerateNumber() {}
#Override
public void run() {
while (running) {
generatedNumber++;
Log.d(TAG, "run: " + generatedNumber);
try {
Intent intent = new Intent();
intent.setAction(MY_ACTION);
intent.putExtra("DATAPASSED", String.valueOf(generatedNumber));
sendBroadcast(intent);
Thread.sleep(500);
if (generatedNumber >= 100) {
running = false;
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}

How to Recieve a stream of data from a native Service's BroadcastReciever using EventChannel?

Let's pretend that I have a flutter application and I have a Foreground Service that has a worker thread and keeps sending me updates about user's location, this is the service's code which returns a random integer numbers for now :
Android Service code
public class LocationUpdatesService extends Service {
static final int NOTIFICATION_ID = 100;
static final String NOTIFICATION = "com.example.fitness_app";
NotificationManagerCompat m_notificationManager;
private Intent m_broadcastInent;
private final String TAG = this.getClass().getSimpleName();
private AtomicBoolean working = new AtomicBoolean(true);
private int steps = 0;
private Runnable runnable = new Runnable() {
#Override
public void run() {
while(working.get()) {
steps++;
m_notificationManager.notify(NOTIFICATION_ID,
createNotification("Steps Counter" + steps ,
R.drawable.common_full_open_on_phone, 1));
m_broadcastInent.putExtra("steps", steps);
sendBroadcast(m_broadcastInent);
}
}
};
#Override
public void onCreate() {
m_broadcastInent = new Intent(NOTIFICATION);
m_notificationManager = NotificationManagerCompat.from(this);
createNotificationChannel();
startForeground(NOTIFICATION_ID, createNotification("Steps Counter" ,
R.drawable.common_full_open_on_phone, 0));
super.onCreate();
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
new Thread(runnable).start();
return Service.START_STICKY;
}
#Override
public void onDestroy() {
working.set(false);
m_notificationManager.cancel(NOTIFICATION_ID);
super.onDestroy();
}
private Notification createNotification(String title, int icon, int steps) {
NotificationCompat.Builder builder = new NotificationCompat.Builder(this,
getString(R.string.BACKGROUND_SERVICE_NOTIFICATION_CHANNEL_ID));
builder.setNumber(steps);
builder.setSmallIcon(icon);
builder.setContentTitle(title);
builder.setOnlyAlertOnce(true);
return builder.build();
}
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = getString(R.string.BACKGROUND_SERVICE_NOTIFICATION_CHANNEL_ID);
String description =
getString(R.string.BACKGROUND_SERVICE_NOTIFICATION_CHANNEL_DESCRIPTION);
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel channel =
new NotificationChannel(getString(
R.string.BACKGROUND_SERVICE_NOTIFICATION_CHANNEL_ID), name, importance);
channel.setDescription(description);
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
}
}
In MainActivity.java I am recieving broadcasts from the service and I should send them to the flutter side:
MainActivity
public class MainActivity extends FlutterActivity {
private static final String TAG = MainActivity.class.getSimpleName();
private static final String ONE_TIME_BACKGROUND_METHOD_CHANNEL = "fitness_app/method_one_time_service";
private static final String EVENTS_STREAM_CHANNEL = "fitness_app/event_one_time_service";
private Intent m_serviceIntent;
private MethodChannel m_methodChannel;
private EventChannel m_eventchannel;
private EventChannel.EventSink m_stepsStreamSink;
private EventChannel.StreamHandler m_eventCallHandler;
private MethodChannel.Result m_result;
private EventChannel.EventSink m_eventSink;
private BroadcastReceiver m_serviceBroadcastReciever = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// Log.d(TAG, "milliseconds " + intent.getIntExtra("steps", 0));
Bundle bundle = intent.getExtras();
if (bundle != null) {
int steps = bundle.getInt("steps");
/////////////////////////////////////////
/////////////////////////////////////////
// I need Here To add Data To the stream
/////////////////////////////////////////
/////////////////////////////////////////
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
GeneratedPluginRegistrant.registerWith(this);
m_serviceIntent = new Intent(this, LocationUpdatesService.class);
PendingIntent pendingIntent = PendingIntent.getService(this, 0, m_serviceIntent, 0);
m_methodChannel = new MethodChannel(getFlutterView(), ONE_TIME_BACKGROUND_METHOD_CHANNEL);
m_methodChannel.setMethodCallHandler(new MethodChannel.MethodCallHandler() {
#Override
public void onMethodCall(MethodCall methodCall, MethodChannel.Result result) {
if (methodCall.method.equals("START_STEPS_COUNTER")) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
startForegroundService(m_serviceIntent);
} else {
startService(m_serviceIntent);
}
} else {
stopService(m_serviceIntent);
}
}
});
m_eventchannel = new EventChannel(getFlutterView(), EVENTS_STREAM_CHANNEL);
m_eventCallHandler = new EventChannel.StreamHandler() {
#Override
public void onListen(Object o, EventChannel.EventSink eventSink) {
m_eventSink = eventSink;
}
#Override
public void onCancel(Object o) {
}
};
m_eventchannel.setStreamHandler(m_eventCallHandler);
}
#Override
protected void onStart() {
super.onStart();
}
#Override
protected void onResume() {
super.onResume();
registerReceiver(m_serviceBroadcastReciever, new IntentFilter(LocationUpdatesService.NOTIFICATION));
}
#Override
protected void onDestroy() {
super.onDestroy();
}
}
Flutter dart code
void start() async {
try {
await _methodChannel.invokeMethod(PlatformMethods.STEPS_COUNTER_START);
Stream<int> stream = _eventChannel.receiveBroadcastStream();
} on PlatformException catch (e) {
print(
" Faild to run native service with thrown exception : ${e.toString()}");
}
Everything here works fine. I can Trigger the service using the Methodchannel, I receive the data from the service using the BroadCastREciever.
All I need to do is to return a stream from the native code using EventChannel.
Create a class that extends BroadcastReceiver and pass a EventChannel.EventSink.
class SinkBroadcastReceiver(private val sink: EventChannel.EventSink) {
override fun onReceive(context: Context, intent: Intent) {
val bundle = intent.getExtras()
if (bundle != null) {
val steps = bundle.getInt("steps")
sink.success(steps)
}
}
}
Then, instead od create the BroadcastReceiver in the declaration you can create it in the onListen and call registerReceiver there:
m_eventCallHandler = new EventChannel.StreamHandler() {
#Override
public void onListen(Object o, EventChannel.EventSink eventSink) {
SinkBroadcastReceiver receiver = new SinkBroadcastReceiver(eventSink);
registerReceiver(receiver, new IntentFilter(LocationUpdatesService.NOTIFICATION));
// TODO : Save receiver in a list to call unregisterReceiver later
}
#Override
public void onCancel(Object o) {
}
};
You may need to track all the receivers in a list because you may need to unregister when the activity stops. Also when you stop the service you may need to traverse the list of registered BroadcastReceiver to unregister all the instances.
This way you may also have more than one listener on the dart code for the same event.

Android internet connectivity across all Android versions

I am looking for a way to check and to listen to my internet connection but since the latest Android version doesn't support registering a broadcast in Manifest, I am looking for a way to implement something that works on all the Android versions. So far I couldn't find any solutions.
I tried adding a Broadcast intent filter into my Manifest file but that's not allowed in the more recent Android versions.
<receiver
android:name="utilities.NetworkStateChangeReceiver"
android:exported="true"
android:enabled="true"
android:label="NetworkConnection" >
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
<action android:name="android.net.wifi.STATE_CHANGE"/>
</intent-filter>
</receiver>
public class NetworkStateChangeReceiver extends BroadcastReceiver {
public static final String NETWORK_AVAILABLE_ACTION = "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);
}
private boolean isConnectedToInternet(Context context) {
final ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
boolean isMobile = false, isWifi = false;
NetworkInfo[] infoAvailableNetworks = cm.getAllNetworkInfo();
if (infoAvailableNetworks != null) {
for (NetworkInfo network : infoAvailableNetworks) {
if (network.getType() == ConnectivityManager.TYPE_WIFI) {
if (network.isConnected() && network.isAvailable())
isWifi = true;
}
if (network.getType() == ConnectivityManager.TYPE_MOBILE) {
if (network.isConnected() && network.isAvailable())
isMobile = true;
}
}
}
return isMobile || isWifi;
}
}
My receiver is not able to receive a broadcast
I'm using pretty much the same logic with IntentFilter and it works for me pretty good without registering it in the Manifest file.
Interface:
public interface IReceiverStateChange {
void register(BroadcastReceiver broadcastReceiver);
void unregister(BroadcastReceiver broadcastReceiver);
}
Implementation:
public class NetworkReceiverStateChange implements IReceiverStateChange {
private Context mContext;
private Boolean mIsRegistered = false;
public NetworkReceiverStateChange(Context context) {
mContext = context;
}
#Override
public void register(BroadcastReceiver broadcastReceiver) {
if (!mIsRegistered) {
IntentFilter netWorkIntentFilter = new
IntentFilter("android.net.conn.CONNECTIVITY_CHANGE");
mContext.registerReceiver(broadcastReceiver, netWorkIntentFilter);
mIsRegistered = true;
}
}
#Override
public void unregister(BroadcastReceiver broadcastReceiver) {
if (mIsRegistered) {
mContext.unregisterReceiver(broadcastReceiver);
mIsRegistered = false;
}
}
}
Register in the desired activity:
if (mNetworkStateChange == null) {
mNetworkStateChange = new NetworkReceiverStateChange(this);
}
mNetworkStateChange.register(mNetworkBroadcastReceiver);
Unregister in onDestroy:
if (mNetworkStateChange != null) {
mNetworkStateChange.unregister(mNetworkBroadcastReceiver);
}
The BroadcastReceiver Obj:
//The CONNECTIVITY_ACTION broadcast seems to be sticky on some devices (even
though the documentation implies that it is not).
// This means that when you register the receiver it will immediately call
onReceive() with the most recently sent broadcast.
private final BroadcastReceiver mNetworkBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (action != null && action.matches("android.net.conn.CONNECTIVITY_CHANGE")) {
<DO SOMETHING>
}
}
};
Hope it helps :)
If you want to check your internet connection all of your activities you can follow below code :-
NetworkSchedulerService.java
public class NetworkSchedulerService extends JobService implements
ConnectivityReceiver.ConnectivityReceiverListener {
private static final String TAG = NetworkSchedulerService.class.getSimpleName();
private ConnectivityReceiver mConnectivityReceiver;
#Override
public void onCreate() {
super.onCreate();
Log.i(TAG, "Service created");
prefManager = PrefManager.getInstance(this);
mConnectivityReceiver = new ConnectivityReceiver(this);
}
/**
* When the app's NetworkConnectionActivity is created, it starts this service. This is so that the
* activity and this service can communicate back and forth. See "setUiCallback()"
*/
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(TAG, "onStartCommand");
return START_NOT_STICKY;
}
#Override
public boolean onStartJob(JobParameters params) {
Log.i(TAG, "onStartJob" + mConnectivityReceiver);
registerReceiver(mConnectivityReceiver, new IntentFilter(CONNECTIVITY_ACTION));
return true;
}
#Override
public boolean onStopJob(JobParameters params) {
Log.i(TAG, "onStopJob");
unregisterReceiver(mConnectivityReceiver);
return true;
}
#Override
public void onNetworkConnectionChanged(boolean isConnected) {
if(isConnected){
Toast.makeText(this,"connected to internet",Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(this,"no internet connection",Toast.LENGTH_SHORT).show();
}
}
}
In manifest file
<service
android:name=".NetworkSchedulerService"
android:exported="true"
android:permission="android.permission.BIND_JOB_SERVICE"/>```
create a Application class
class MyApplication extends Application {
override fun onCreate() {
super.onCreate()
scheduleJob()
}
override fun onStop() {
super.onStop()
// A service can be "started" and/or "bound". In this case, it's "started" by this Activity
// and "bound" to the JobScheduler (also called "Scheduled" by the JobScheduler). This call
// to stopService() won't prevent scheduled jobs to be processed. However, failing
// to call stopService() would keep it alive indefinitely.
stopService(Intent(this, NetworkSchedulerService::class.java))
}
override fun onStart(){
val startServiceIntent = Intent(this, NetworkSchedulerService::class.java)
startService(startServiceIntent)
}
private fun scheduleJob() {
val myJob = JobInfo.Builder(0, ComponentName(this, NetworkSchedulerService::class.java))
.setRequiresCharging(true)
.setMinimumLatency(1000)
.setOverrideDeadline(2000)
.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)
.setPersisted(true)
.build()
val jobScheduler = getSystemService(Context.JOB_SCHEDULER_SERVICE) as JobScheduler
jobScheduler.schedule(myJob)
}
}
define application class in manifest file
BroadcastReceiver class ->
public class ConnectivityReceiver extends BroadcastReceiver {
private ConnectivityReceiverListener mConnectivityReceiverListener;
ConnectivityReceiver(ConnectivityReceiverListener listener) {
mConnectivityReceiverListener = listener;
}
#Override
public void onReceive(Context context, Intent intent) {
mConnectivityReceiverListener.onNetworkConnectionChanged(isConnected(context));
}
public static boolean isConnected(Context context) {
ConnectivityManager cm = (ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
return activeNetwork != null && activeNetwork.isConnectedOrConnecting();
}
public interface ConnectivityReceiverListener {
void onNetworkConnectionChanged(boolean isConnected);
}
}
**onNetworkConnectionChanged will notify when internet is connected or not (NetworkSchedulerService.java)
Don't define BroadCastReceiver in manifest file. make sure to provide internect permission , CHANGE_NETWORK_STATE,ACCESS_NETWORK_STATE
**
I hope this will help you. Let me know if there is any problem. Happy Coding :-)

How can disable hardware HomeKey and BackKey and Recent Butoom in Android Programitcaly

I'm setting a new app and want to disable hardware key like home,back and recent key in my app. I found some code in stackoverflow but none of them work.
Is it possible to disable hardware key?
public class MainActivity extends AppCompatActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
}
public void onAttachedToWindow() {
this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD_DIALOG);
KeyguardManager keyguardManager = (KeyguardManager) getSystemService(KEYGUARD_SERVICE);
KeyguardManager.KeyguardLock lock = keyguardManager.newKeyguardLock(KEYGUARD_SERVICE);
lock.disableKeyguard();
}
}
do nothing in onBackPressed()
#Override
public void onBackPressed() {
}
add this in manifest
<uses-permission android:name="android.permission.REORDER_TASKS" />
and add this in onPause()
#Override
protected void onPause() {
super.onPause();
ActivityManager activityManager = (ActivityManager) getApplicationContext()
.getSystemService(Context.ACTIVITY_SERVICE);
activityManager.moveTaskToFront(getTaskId(), 0);
}
In your MainActivity -
#Override
public void onBackPressed() {
// super.onBackPressed(); commented this line in order to disable back press
//Write your code here
Toast.makeText(getApplicationContext(), "Back press disabled!", Toast.LENGTH_SHORT).show();
}
You can not block Recent and Home but you can restart activity if user click on Home.
Here is example
HomeWatcher Class
public class HomeWatcher {
static final String TAG = "hg";
private Context mContext;
private IntentFilter mFilter;
private OnHomePressedListener mListener;
private InnerRecevier mRecevier;
public HomeWatcher(Context context) {
mContext = context;
mFilter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
}
public void setOnHomePressedListener(OnHomePressedListener listener) {
mListener = listener;
mRecevier = new InnerRecevier();
}
public void startWatch() {
if (mRecevier != null) {
mContext.registerReceiver(mRecevier, mFilter);
}
}
public void stopWatch() {
if (mRecevier != null) {
mContext.unregisterReceiver(mRecevier);
}
}
class InnerRecevier extends BroadcastReceiver {
final String SYSTEM_DIALOG_REASON_KEY = "reason";
final String SYSTEM_DIALOG_REASON_GLOBAL_ACTIONS = "globalactions";
final String SYSTEM_DIALOG_REASON_RECENT_APPS = "recentapps";
final String SYSTEM_DIALOG_REASON_HOME_KEY = "homekey";
final String SYSTEM_DIALOG_REASON_LONG_PRESS = "assist";
final String SYSTEM_DIALOG_REASON_VOICE_INTERACTION = "voiceinteraction";
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) {
String reason = intent.getStringExtra(SYSTEM_DIALOG_REASON_KEY);
if (reason != null) {
Log.e(TAG, "action:" + action + ",reason:" + reason);
if (mListener != null) {
if (reason.equals(SYSTEM_DIALOG_REASON_HOME_KEY)) {
mListener.onHomePressed();
} else if (reason.equals(SYSTEM_DIALOG_REASON_RECENT_APPS)) {
mListener.onHomeLongPressed();
} else if (reason.equals(SYSTEM_DIALOG_REASON_LONG_PRESS)) {
mListener.onHomeLongPressed();
} else if (reason.equals(SYSTEM_DIALOG_REASON_VOICE_INTERACTION)) {
mListener.onHomeLongPressed();
}
}
}
}
}
}
OnHomePressedListener interface
public interface OnHomePressedListener {
void onHomePressed();
void onHomeLongPressed();
}
In Your Main Activity
HomeWatcher mHomeWatcher = new HomeWatcher(this);
mHomeWatcher.setOnHomePressedListener(new OnHomePressedListener() {
#Override
public void onHomePressed() {
Log.d("Pressed", "Home Button Pressed");
}
#Override
public void onHomeLongPressed() {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
Log.d("LongPressed", "Home Long Button Pressed");
}
});
mHomeWatcher.startWatch();

Unable to display and show AlertDialog in BroadcastReceiver in android

public class MySingleton {
private static MySingleton instance;
AlertDialog.Builder builder;
boolean alertDisplayed;
public static MySingleton getInstance() {
if (instance == null) {
instance = new MySingleton();
}
return instance;
}
private MySingleton() {
}
public void displayAlertDialog(final Activity context) {
builder =
new AlertDialog.Builder(context);
final String action = Settings.ACTION_LOCATION_SOURCE_SETTINGS;
final String message = "Enable either GPS or any other location"
+ " service to find current location. Click OK to go to"
+ " location services settings to let you do so.";
builder.setMessage(message).setCancelable(false)
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface d, int id) {
context.startActivityForResult(new Intent(action), 1);
d.dismiss();
}
})
.setNegativeButton("Retry",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface d, int id) {
context.finish();
}
});
builder.create().show();
alertDisplayed = true;
}
public void dismissDialog() {
if (alertDisplayed && builder != null) {
//dismiss dialog
dismissDialog();
}
alertDisplayed = false;
}
}
BroadcastReceiver updateBooleanBroadCastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
if (intent.getBooleanExtra("action", true)) {
//here i want to hide Alert
} else {
//Here i want to display Alert
}
}
};
i have Make class Singlton where i have write code to show and hide method of Alert box and also i have received Event but i am unable to call Singsong class to show and hide Alert please help me how to get this .

Categories

Resources