I have this app which parses SMS and then converts them into Audio. My app users usually minimize the app and runs it all the time. But my app is getting terminated after sometime. How can i make sure my app will run till a user "terminates" it. Since the core functionality of the app is to convert SMS to audio, i need it running all the time.How can i do this ?
My current MainActivity.java
public class MainActivity extends AppCompatActivity {
TextView txtGateway, txtTime, txtAmount;
Speakerbox speakerbox;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//textView = findViewById(R.id.txt_message);
speakerbox = new Speakerbox(getApplication());
txtAmount = findViewById(R.id.tv_amount);
txtGateway = findViewById(R.id.tv_gateway);
txtTime = findViewById(R.id.tv_time);
requestSmsPermission();
}
#Override
public void onResume() {
LocalBroadcastManager.getInstance(this).registerReceiver(receiver, new IntentFilter("otp"));
super.onResume();
}
#Override
public void onPause() {
LocalBroadcastManager.getInstance(this).registerReceiver(receiver, new IntentFilter("otp"));
super.onPause();
}
private BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equalsIgnoreCase("otp")) {
final String message = intent.getStringExtra("message");
String gateway = intent.getStringExtra("gateway");
String time = intent.getStringExtra("time");
String amount = intent.getStringExtra("amount");
speakerbox.play(message);
txtGateway.setText(gateway);
txtTime.setText(time);
txtAmount.setText(amount);
// message is the fetching OTP
}
}
};
/**
* Requesting multiple permissions (storage and location) at once
* This uses multiple permission model from dexter
* On permanent denial opens settings dialog
*/
private void requestSmsPermission() {
Dexter.withActivity(this)
.withPermissions(
Manifest.permission.RECEIVE_SMS,
Manifest.permission.READ_SMS,
Manifest.permission.SEND_SMS,
Manifest.permission.WRITE_EXTERNAL_STORAGE)
.withListener(new MultiplePermissionsListener() {
#Override
public void onPermissionsChecked(MultiplePermissionsReport report) {
// check if all permissions are granted
if (report.areAllPermissionsGranted()) {
// Toast.makeText(getApplicationContext(), "All permissions are granted!", Toast.LENGTH_SHORT).show();
}
// check for permanent denial of any permission
if (report.isAnyPermissionPermanentlyDenied()) {
// show alert dialog navigating to Settings
showSettingsDialog();
}
}
#Override
public void onPermissionRationaleShouldBeShown(List<PermissionRequest> permissions, PermissionToken token) {
token.continuePermissionRequest();
}
}).
withErrorListener(new PermissionRequestErrorListener() {
#Override
public void onError(DexterError error) {
Toast.makeText(getApplicationContext(), "Error occurred! ", Toast.LENGTH_SHORT).show();
}
})
.onSameThread()
.check();
}
/**
* Showing Alert Dialog with Settings option
* Navigates user to app settings
* NOTE: Keep proper title and message depending on your app
*/
private void showSettingsDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Need Permissions");
builder.setMessage("This app needs permission to use this feature. You can grant them in app settings.");
builder.setPositiveButton("GOTO SETTINGS", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
openSettings();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
}
// navigating user to app settings
private void openSettings() {
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
Uri uri = Uri.fromParts("package", getPackageName(), null);
intent.setData(uri);
startActivityForResult(intent, 101);
}
}
Use a foreground service to ensure that your app is not killed by Android. On newer version of Android, app's background process gets killed after sometime. Having a foreground service will ensure that your app stays active. Keep the service on background thread and not on the main thread.
Read more at:
https://developer.android.com/guide/components/services
and
https://androidwave.com/foreground-service-android-example/
Activities are used for user facing parts of your application. Use service instead. Most likely, your application is getting terminated by os due to low memory situation.
Use service for the core functionality if you want to run all the time in background.If user is not using your app actively yet app is taking RAM memory then OS will terminate the app to avoid out of memory.
Related
I'm migrating an app from the play store to the Amazon App store, considering that in this way it will be avilable for Windows 11 too.
For this to make something very fast and easy i made an activity called PurchaseActivity which contains the codes brought by the amazon IAP guide PDF.
The activity is called from a "buy now" button of a dialog window with the following code:
public class PurchaseActivity extends Activity {
String parentSKU = "com.amazon.sample.iap.subscription.mymagazine";
//Define UserId and MarketPlace
private String currentUserId;
private String currentMarketplace;
private ProgressDialog progress;
#Override
protected void onStart(){
super.onStart();
progress = new ProgressDialog(this);
progress.setTitle("Purchasing");
progress.setMessage("Wait while making the purchase...");
progress.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
progress.dismiss();//dismiss dialog
finish();
}
});
progress.setCancelable(false); // disable dismiss by tapping outside of the dialog
progress.show();
PurchasingService.registerListener(this, purchasingListener);
PurchasingService.purchase(parentSKU);
}
#Override
protected void onResume() {
super.onResume();
//getUserData() will query the Appstore for the Users information
PurchasingService.getUserData();
//getPurchaseUpdates() will query the Appstore for any previous purchase
PurchasingService.getPurchaseUpdates(true);
//getProductData will validate the SKUs with Amazon Appstore
final Set<String> productSkus = new HashSet<String>();
productSkus.add(parentSKU);
PurchasingService.getProductData(productSkus);
Log.v("Validating SKUs", "Validating SKUs with Amazon");
}
PurchasingListener purchasingListener = new PurchasingListener() {
#Override
public void onUserDataResponse(UserDataResponse response) {
final UserDataResponse.RequestStatus status = response.getRequestStatus();
switch (status) {
case SUCCESSFUL:
currentUserId = response.getUserData().getUserId();
currentMarketplace = response.getUserData().getMarketplace();
Log.v("IAP SDK", "loaded userdataResponse");
break;
case FAILED:
case NOT_SUPPORTED:
// Fail gracefully.
Log.v("IAP SDK", "loading failed");
break;
}
}
#Override
public void onProductDataResponse(ProductDataResponse productDataResponse) {
switch (productDataResponse.getRequestStatus()) {
case SUCCESSFUL:
//get informations for all IAP Items (parent SKUs)
final Map<String, Product> products = productDataResponse.getProductData();
for (String key : products.keySet()) {
Product product = products.get(key);
Log.v("Product:", String.format("Product: %s\n Type: %s\n SKU: %s\n Price: %s\n Description: %s\n", product.getTitle(), product.getProductType(),
product.getSku(), product.getPrice(), product.getDescription()));
}
//get all unavailable SKUs
for (String s : productDataResponse.getUnavailableSkus()) {
Log.v("Unavailable SKU:" + s, "Unavailable SKU:" + s);
}
break;
case FAILED:
Log.v("FAILED", "FAILED");
progress.dismiss();
finish();
break;
}
}
#Override
public void onPurchaseResponse(PurchaseResponse purchaseResponse) {
switch (purchaseResponse.getRequestStatus()) {
case SUCCESSFUL:
PurchasingService.notifyFulfillment(purchaseResponse.getReceipt().getReceiptId(),
FulfillmentResult.FULFILLED);
break;
case FAILED:
progress.dismiss();
finish();
break;
}
}
#Override
public void onPurchaseUpdatesResponse(PurchaseUpdatesResponse response) {
// Process receipts
switch (response.getRequestStatus()) {
case SUCCESSFUL:
for (final Receipt receipt : response.getReceipts()) {
// Process receipts
if (!receipt.isCanceled()) {
// sharedprefs
SharedPreferences sharedPreference = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor sharedPrefEditor = sharedPreference.edit();
sharedPrefEditor.putBoolean("isPro",true);
sharedPrefEditor.apply();
progress.dismiss();
finish();
}
}
if (response.hasMore()) {
PurchasingService.getPurchaseUpdates(true);
}
break;
case FAILED:
Log.d("FAILED", "FAILED");
progress.dismiss();
finish();
break;
}
}
};
}
Yeah i know i should not call all that stuff in the onStart() method but i'll make an onCreate() with a UI later.
As you can see from this code, i'm testing in sandbox mode.
THE PROBLEM: Actually when the activity starts, i see progressDialog, and i read in the debug logs that "V/Validating SKUs: Validating SKUs with Amazon" but i don't see then the amazon buy window. It also seems like the listener code is never called, even if i put some breakpoints in there, they're never reached which is very weird considering that apprently it gets initialized and called successfully by the method "PurchasingService.registerListener(this, purchasingListener)"
Any help would be very apreciated!
Thanks and have a good evening
You need to call registerListener in your Application's onCreate, otherwise Amazon fails to detect there's an Activity being displayed and it will not show the purchase dialog.
So I'm working for a company that requires a VPN in order to connect to the database server. I'm facing an issue with disconnecting programmatically from the VPN service (or disabling it) upon onPause / onStop.
In order to ensure the user is indeed connected to a VPN, I'm using a network listener and if the user is not connected, a dialog is being shown and navigates the user to the VPN Settings Configuration. Once the user connects and resumes the application, the listener recognizes the VPN IP and everything runs great.
My issue is that I want to disable the VPN connection once the user has stopped using the application. Therefore, I've been trying to search for a solution that disables the VPN connection without requesting the user to go to the VPN Settings again. Is there an option to toggle the VPN off programmatically without navigating to the VPN Settings page?
Network Service:
public class NetworkSchedulerService extends JobService implements
ConnectivityReceiver.ConnectivityReceiverListener {
private ConnectivityReceiver mConnectivityReceiver;
#Override
public void onCreate() {
super.onCreate();
mConnectivityReceiver = new ConnectivityReceiver(this);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_NOT_STICKY;
}
#Override
public boolean onStartJob(JobParameters params) {
registerReceiver(mConnectivityReceiver, new IntentFilter(Constants.CONNECTIVITY_ACTION));
return true;
}
#Override
public boolean onStopJob(JobParameters params) {
unregisterReceiver(mConnectivityReceiver);
return true;
}
#Override
public void onNetworkConnectionChanged(boolean isConnected) {
String message = isConnected ? "מחובר לרשת" : "אין חיבור פעיל לרשת";
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
}
}
Listener:
private void scheduleJob() {
JobInfo myJob = new JobInfo.Builder(0, new ComponentName(this, NetworkSchedulerService.class))
.setRequiresCharging(true)
.setMinimumLatency(1000)
.setOverrideDeadline(2000)
.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)
.setPersisted(true)
.build();
JobScheduler jobScheduler = (JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE);
jobScheduler.schedule(myJob);
}
#Override
protected void onStop() {
stopService(new Intent(this, NetworkSchedulerService.class));
super.onStop();
}
#Override
protected void onStart() {
super.onStart();
Intent startServiceIntent = new Intent(this, NetworkSchedulerService.class);
startService(startServiceIntent); // INTERNET LISTENER
}
Dialog:
public void dialogVPN() {
builder = new AlertDialog.Builder(LoadingSplash.this);
builder.setMessage("Please ensure VPN Connection");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent("android.net.vpn.SETTINGS");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivityForResult(intent, 10);
}
});
builder.show();
}
And the returnConnType:
public String returnConnType() {
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(this.CONNECTIVITY_SERVICE);
String result = "None";
if (connectivityManager != null) {
Network network = connectivityManager.getActiveNetwork();
NetworkCapabilities capabilities = connectivityManager.getNetworkCapabilities(network);
if (capabilities == null) {
result = "None";
}
if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
result = "WIFI";
} else if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
result = "MOBILE";
} else if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_VPN)) {
result = "VPN";
}
}
return result;
}
Any suggestions as to how to solve this? A proper solution or an alternative one would be appreciated.
I don't think you can disable the VPN settings from inside the app using an API provided by Android, as I do not know about any such APIs. However, as a workaround, you can consider doing the following.
While exiting the application (on a back button press), you can use the same listener to pop up another dialog saying the user to turn off the VPN. Hence, turning off the VPN will follow the same tasks that the user had to do while turning on the VPN.
When a user exits the application using a home button press, you might consider using a JobScheduler in your onDestroy function of the exiting activity, so that you can check if the VPN connection is alive in a background service when the application is not running and create a notification which will tell the user that, the VPN is alive. Then on clicking the notification, redirect the user to the VPN configuration settings and guide the user to turn it off.
Hope that helps!
So thanks to #Reaz I've managed to find the proper solution for now.
Tested on Oreo
In case someone else is intrested..
app
implementation 'android.arch.lifecycle:extensions:1.1.1'
AppLifecycleObserver
public class AppLifecycleObserver extends MultiDexApplication implements LifecycleObserver {
public static final String TAG = AppLifecycleObserver.class.getName();
Notifications notif = new Notifications();
Context mContext;
public AppLifecycleObserver(Context context) {
mContext = context;
}
#OnLifecycleEvent(Lifecycle.Event.ON_START)
public void onEnterForeground() {
Log.v(TAG,"FOREGROUND");
}
#OnLifecycleEvent(Lifecycle.Event.ON_STOP)
public void onEnterBackground() {
Log.v(TAG,"BACKGROUND");
notif.createVPNNotification(mContext,"VPN","Please make sure to turn VPN off");
}
}
on Any activity you wish to implement # onCreate:
AppLifecycleObserver appLifecycleObserver = new AppLifecycleObserver(this);
ProcessLifecycleOwner.get().getLifecycle().addObserver(appLifecycleObserver);
I'm trying to code some unit test for some OnCreate() methode on my XMPP app on android Studio, the problem is that i have never done that and i'm a little bit lost.
Here is my methode :
public class ChatActivity extends AppCompatActivity {
private static final String TAG ="ChatActivity";
private String contactJid;
private ChatView mChatView;
private SendButton mSendButton;
private BroadcastReceiver mBroadcastReceiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
mChatView =(ChatView) findViewById(R.id.rooster_chat_view);
mChatView.setEventListener(new ChatViewEventListener() {
#Override
public void userIsTyping() {
//Here you know that the user is typing
}
#Override
public void userHasStoppedTyping() {
//Here you know that the user has stopped typing.
}
});
mSendButton = mChatView.getSendButton();
mSendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Only send the message if the client is connected
//to the server.
if (RoosterConnectionService.getState().equals(RoosterConnection.ConnectionState.CONNECTED)) {
Log.d(TAG, "The client is connected to the server,Sending Message");
//Send the message to the server
Intent intent = new Intent(RoosterConnectionService.SEND_MESSAGE);
intent.putExtra(RoosterConnectionService.BUNDLE_MESSAGE_BODY,
mChatView.getTypedString());
intent.putExtra(RoosterConnectionService.BUNDLE_TO, contactJid);
sendBroadcast(intent);
//Update the chat view.
mChatView.sendMessage();
} else if (RoosterConnectionService.getState().equals(RoosterConnection.ConnectionState.DISCONNECTED)){
Toast.makeText(getApplicationContext(),
"Client not connected to server ,Message not sent!",
Toast.LENGTH_LONG).show();
}
}
});
Intent intent = getIntent();
contactJid = intent.getStringExtra("EXTRA_CONTACT_JID");
setTitle(contactJid);
}
My question is that i don't know how to proceed and what to put in my OnCreateTest() method and what to test, could anyone help please :(
I have a notepad activity that opens up a window dialog version of it where user can go to another app and still type on the notepad
For both notepad to have the same content, I used broadcastReceiver to set the text of the notepad activity to the one in the dialog when the user is done.
Activity's BroadcastReceiver:
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
final globalVariable globalVariable = (globalVariable) getApplicationContext();
et_editor.setText(globalVariable.getScriptEditorText());
Toast.makeText(Script_editor.this, "Script Editor have been updated", Toast.LENGTH_SHORT).show();
}
};
Close Button of the Dialog:
btn_Close = (Button) view.findViewById(R.id.button_Close);
btn_Close.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog alertDialog = new AlertDialog.Builder(getApplicationContext())
.setTitle("Would you like to update the editor?")
.setNegativeButton("No, discard the changes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(ColorCoordinatePickerService.this, "Changes have been discarded", Toast.LENGTH_SHORT).show();
dialog.dismiss();
stopSelf();
}
})
.setPositiveButton("Yes, update with changes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
final globalVariable globalVariable = (globalVariable) getApplicationContext();
globalVariable.setScriptEditortext(CCEditor.getText().toString());
Intent intent = new Intent(BROADCAST_ACTION);
sendBroadcast(intent);
dialog.dismiss();
stopSelf();
}
})
.create();
alertDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
alertDialog.show();
}
});
It works BUT the user have to go back to the notepad activity (cannot be in another app or activity).
How do I update the notepad's content without having to "open" it up?
Queue the changes in BroadcastReceiver and when NotepadActivity resumes set the changes in the EditText. The queue doesn't need to be an actual queue, you can persist the last broadcast receiver data somewhere.
I am not sure, but it may be clear your global variable on moving from activity to another activity, also you are declaring the instance of global variable so it will set value in instance not in main variable and therefor you will not get it on receiver.
So I think you should set value in intent and then get it on receiver and manage it so it will work.
Check below, first your click event of dialog box method
#Override
public void onClick(DialogInterface dialog, int which) {
final globalVariable globalVariable = (globalVariable) getApplicationContext();
globalVariable.setScriptEditortext(CCEditor.getText().toString());
Intent intent = new Intent(BROADCAST_ACTION);
intent.putExtra("global_variable","" + CCEditor.getText().toString());
sendBroadcast(intent);
dialog.dismiss();
stopSelf();
}
And now get value in receiver as like below.
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
final globalVariable globalVariable = (globalVariable) getApplicationContext();
String strData = intent.getExtras().getString("global_variable");
et_editor.setText(strData);
Toast.makeText(Script_editor.this, "Script Editor have been updated", Toast.LENGTH_SHORT).show();
}
};
Hope this will work
without opening acitivity,you want to update data then only one way you can do it.when you receive in receiver set all data into sharepreference.Whenever your notepad activity opens you can set take data from sharepreference and set it into notepad activity.
Use LocalBroadcastManager.
Example: How to use it
AlertDialog from within BroadcastReceiver? Can it be done? I am working on a app that will pop up a Dialog box if I get SMS message. I am trying to code this within a BroadcaseReceiver. But I cant use this line of code AlertDialog.Builder builder = new AlertDialog.Builder(this);. Can someone please help me with a hint!
public class SMSPopUpReceiver extends BroadcastReceiver {
private static final String LOG_TAG = "SMSReceiver";
public static final int NOTIFICATION_ID_RECEIVED = 0x1221;
static final String ACTION = "android.provider.Telephony.SMS_RECEIVED";
public void onReceive(Context context, Intent intent) {
Log.i(LOG_TAG, "onReceive");
if (intent.getAction().equals(SMSPopUpReceiver.ACTION)) {
StringBuilder sb = new StringBuilder();
Bundle bundle = intent.getExtras();
if (bundle != null) {
Object[] pdus = (Object[]) bundle.get("pdus");
for (Object pdu : pdus){
SmsMessage messages =
SmsMessage.createFromPdu((byte[]) pdu);
sb.append("Received SMS\nFrom: ");
sb.append(messages.getDisplayOriginatingAddress());
sb.append("\n----Message----\n");
sb.append( messages.getDisplayMessageBody());
}
}
Log.i(SMSPopUpReceiver.LOG_TAG,
"[SMSApp] onReceiveIntent: " + sb);
Toast.makeText
(context, sb.toString(), Toast.LENGTH_LONG).show();
}
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Are you sure you want to exit?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
}
}
Principal issue: try to avoid placing time consuming functionalities into BroadcastReceiver. It should just receive and initiate further processing in bound Activity/Service.
UPDATE:
Please check following sources that might be helpful:
Similar questions on StackOverflow:
How to send data from BroadcastReceiver to an Activity in android?
Android SMS receiver not working
Android SDK demo example:
android-sdk-windows\samples\android-8\ApiDemos\src\com\example\android\apis\os\SmsMessagingDemo.java
And of course standard Android API documentation: http://developer.android.com/reference/android/content/BroadcastReceiver.html
UPDATE2:
Added app skeleton as it should look. Please note that no content view is defined. It is because your app will have transparent screen. To achieve that
#android:style/Theme.Translucent
is entered under Theme tag for this activity in AndroidManifest.xml.
public class NotifySMSReceived extends Activity
{
private static final String LOG_TAG = "SMSReceiver";
public static final int NOTIFICATION_ID_RECEIVED = 0x1221;
static final String ACTION = "android.provider.Telephony.SMS_RECEIVED";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
IntentFilter filter = new IntentFilter(ACTION);
this.registerReceiver(mReceivedSMSReceiver, filter);
}
private void displayAlert()
{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Are you sure you want to exit?").setCancelable(
false).setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
}).setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
private final BroadcastReceiver mReceivedSMSReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (ACTION.equals(action))
{
//your SMS processing code
displayAlert();
}
}
};
}
I've been looking into it and the documentation of the BroadcastReceiver actually says:
public abstract void onReceive
(Context context, Intent intent)
Since: API Level 1 This method is
called when the BroadcastReceiver is
receiving an Intent broadcast. During
this time you can use the other
methods on BroadcastReceiver to
view/modify the current result values.
The function is normally called within
the main thread of its process, so you
should never perform long-running
operations in it (there is a timeout
of 10 seconds that the system allows
before considering the receiver to be
blocked and a candidate to be killed).
You cannot launch a popup dialog in
your implementation of onReceive().
You cannot launch a popup dialog in
your implementation of onReceive()
So it seems it is not possible
This is late but this may help someone.
You cannot use alert dialog inside broadcast receiver, we can use this only in activity or service. Try like this
In your onReceive method of broadcastreceiver add
Intent i = new Intent(context, yourclass.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
and in yourclass set your dialog message, so that it will appear when you trigger the receiver event. I tried this and it worked me. Hope this may help some one :-)
you can create a new transparent activity and then create Alert Dialog in that activity, whenever your alert is to be displayed call that activity from your broadcast reciever ,this could work, not tested
replace the word "this" inside the AlertDilaog with "context" -- the first parameter on you onRecieve method.
public void onReceive(Context context, Intent intent)