Hi i'm looking to kill an activity in my application when the usb is disconnected i have a broadcast receiver and all set up and working fine
public class USBOff extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Intent intent1 = new Intent(context, SdcardOff.class);
startActivity(intent1);
finish();
}
}
This code however tells me that the finish method and startActivity methods need to be created? why is this not working thank you for any help with my problem
startActivity is a Context method, not a BroadcastReceiver method. finish is an Activity method. Try this:
context.startActivity(intent1);
You can't call finish from a BroadcastReceiver.
I have found an interexting method :
Manfest :
android:launchMode="singleInstance"
<action android:name="com.gr.app.KILLSELF" />
receiver code :
Intent intentInterface = new Intent("com.gr.app.KILLSELF");
mContext.startActivity(intentInterface);
activity onCreate part :
if (intent.getAction().compareTo("com.gr.app.KILLSELF") == 0) {
finish();
};
It will not work in such configuration if you may have many instancesof activity (string android:launchMode="singleInstance" is a problem for you),
I hope it will help
Simple Logic :
If you dont want to kill the activity then do not use finish() And if you want to kill the activity then you should have to call finish();
So remove the finish(); from code and try it out.
Enjoy.
Related
I have an application that using "AlarmService". For handling alarms i have a Broadcast receiver. That receiver has to start certain activity. Code i'm using for achieving that is following:
#Override
public void onReceive(Context context, Intent intent) {
...other code....
Intent intIntent = new Intent(context, MainActivity.class);
intIntent .putExtra("IsAlarm", true);
Intent alarmChooser = Intent.createChooser(intIntent , "Alarm");
alarmChooser.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(alarmChooser);
}
That works but only if activity isn't shown already (if it's not in the foreground). If called activity is already opened nothing happens. How can i overcome that?
Is there a flag that will start the activity if it's not started OR send intent to it even if it's in the foreground?
P.S. i tried using dedicated "broadcast" above the provided code. Reciever for that broadcast is registered programmatically in the MainActivity: "onResume" would register dedicated receiver, "onPause" would unregister it. That way in case MainActivity is already on it will receive a broadcast but then i have a problem when phone goes to "stand by" - "dedicated" receiver is unregistered.
Check in the activity onNewIntent callback
there should be the new intent from the receiver
I think you don't need the chooser:
#Override
public void onReceive(Context context, Intent intent) {
Intent intIntent = new Intent(context, MainActivity.class);
intIntent.putExtra("IsAlarm", true);
context.startActivity(intIntent);
}
Well, my question is just as simple as in the title:
Is there a way to call finish() on all running activities inside application ?
So i need a way to completly shut down my app.
You can achieve that with a BroadCastReceiver:
In every activity put:
private BroadcastReceiver mLoggedOutReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
finish();
}
};
Register receiver in onCreate:
registerReceiver(mLoggedOutReceiver, new IntentFilter(Preferences.INTENT_ACTION_LOGGED_OUT));
on onDestroy:
#Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(mLoggedOutReceiver);
}
on manifest for every activity and the following filter:
<intent-filter>
<action android:name="com.example.intent.action.LOGGED_OUT" />
</intent-filter>
I have the intent Action declared in Preference class like this:
public static final String INTENT_ACTION_LOGGED_OUT = "com.example.intent.action.LOGGED_OUT";//logout
And finally all you have to do is call sendBroadcast from an exit button or something:
sendBroadcast(new Intent(Preferences.INTENT_ACTION_LOGGED_OUT));//logout
Hope this helps.
android.os.Process.killProcess(android.os.Process.myPid());
this code can shut down your app.
NO
but you can exist hole application like System.exit(0); but it is not the recomanded way..as android not design to exit the application.
The parts of this application in question are an IntentService (DatabaseService) and an AppWidgetProvider (LotWidget). In LotWidget, when a button is pressed, a PendingIntent is fired which sends a broadcast to itself, and is received in onReceive(). All of this works fine so far. In onReceive, I read the action from the Intent as well as the various extras, and either start this IntentService, or start the main Activity. Starting the activity works fine, but for some reason I can't understand, the DatabaseService isn't being started. I know code leading up to the DatabaseService intent is being sent by testing with Log.
Here is the onReceive code:
#Override
public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);
if(intent.getAction().equals(RETURN_DATA_WIDGET) && initialize(context)){
updateWidget(context);
}
else if(intent.getAction().equals(INTERNAL_INC)){
Log.d("WIDG", "Incrememnt");
Intent incr = new Intent(context, DatabaseService.class);
incr.setAction(INCREMENT);
incr.putExtra("incval", intent.getIntExtra("incval", 999));
context.startService(intent);
}
else if(intent.getAction().equals(INTERNAL_UP)){
Log.d("WIDG", "UPDATE");
Intent upd = new Intent(context, DatabaseService.class);
upd.setAction(UPDATE_COUNT);
context.startService(intent);
}
else if(intent.getAction().equals(OPEN_APP)){
Intent open = new Intent(context, TheLotActivity.class);
open.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(open);
}
}
Using the same intents to start the DatabaseService from the main Activity works fine. My manifest defines the DatabaseService as a Service like so:
<service android:name="com.bsprague.thelot.DatabaseService" >
</service>
I know the Service isn't being started because a Log at the very beginning of onHandleIntent isn't being displayed, though it displays fine when this Intent is sent from the main Activity. Is there something in Android that I'm missing that makes it so you can't start a Service from a BroadcastReceiver?
You are setting an action on the Intent, and your <intent-filter> does not have that action. You might consider replacing the setAction() calls with putExtra() calls instead.
Never mind -- as you pointed out in a comment, since you are specifying the component, all other routing elements (e.g., action) are ignored. Your error from your updated comment suggests that your Intent is picking up the wrong component, LotWidget instead of DatabaseService.
I am launching activity from the service based on some value got from the server and the activity will be displayed for the some time and after getting close instruction from the server i need to close that activity,so for that i used following approach but it's not working:
on Service class:
if(((ActivityManager)this.getSystemService(ACTIVITY_SERVICE)).getRunningTasks(1).get(0).topActivity.getPackageName().equals("com")) {
if(((ActivityManager)this.getSystemService(ACTIVITY_SERVICE)).getRunningTasks(1).get(0).topActivity.getClassName().equals("com.CustomDialogActivity")){
Intent dialogIntent = new Intent(getBaseContext(), CustomDialogActivity.class);
dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
dialogIntent.putExtra("description", "");
dialogIntent.putExtra("cancelEnabled", false);
dialogIntent.putExtra("close", true);
getApplication().startActivity(dialogIntent);
}
}
and on activity inside onCreate method:
Bundle bundle = getIntent().getExtras();
boolean isClosed = bundle.getBoolean("close");
if(isClosed){
finish();
}
I debugged it and found that control reaches to the onCreate method if(isClosed) condition and executed finish() method also but its not closing the activity.
so Couldn't be able to analyze what wrong I am doing.
Write a broadcast receiver in your CustomDialogActivity like following.
private final BroadcastReceiver abcd = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
finish();
}
};
Then register it in the same file like the following:
onCreate(){
registerReceiver(abcd, new IntentFilter("xyz"));
}
Unregister it in onDestroy.
onDestroy(){
//unRegister
}
Now,Whenever you want to close that Activity just call like the following.
sendBroadcast(new Intent("xyz"));
Hope this help.
You must add the receiver into the manifest for your activity, For example :
<activity android:name="MyActivity">
<intent-filter>
<action android:name="xyz" />
</intent-filter>
</activity>
Try to send broadcast using context.
context.sendBroadcast(new Intent("xyz"));
Answer from Jainal is Working for me.
In my app, I have an Activity from which I want to start a Service. Can anybody help me?
Add this in your code
Intent serviceIntent = new Intent(this, ServiceName.class);
startService(serviceIntent);
Dont forget to add service tag in AndroidManifest.xml file
<service android:name="com.example.ServiceName"></service>
From the Android official documentation:
Caution: A service runs in the same process as the application in
which it is declared and in the main thread of that application, by
default. So, if your service performs intensive or blocking operations
while the user interacts with an activity from the same application,
the service will slow down activity performance. To avoid impacting
application performance, you should start a new thread inside the
service.
The application can start the service with the help of the Context.startService method. The method will call the onCreate method of the service if service is not already created; else onStart method will be called. Here is the code:
Intent serviceIntent = new Intent();
serviceIntent.setAction("com.testApp.service.MY_SERVICE");
startService(serviceIntent);
First create service from android Manifest.xml file (i.e from application tab) and give some name to it.
On the activity on some event like click or touch to include the code from the service:
public void onClick(View v)
{
startService(new Intent(getApplicationContext(),Servicename.class));
}
If you want to stop the running or started service then include this code:
public void onclick(View v)
{
stopService(new Intent(getApplicationContext,Servicename.class));
}
The API Demos have some examples that launch services.
Use a Context.startService() method.
And read this.
in kotlin you can start service from activity as follow :
startService!!.setOnClickListener { startService() }
private fun startService(){
startService(Intent(this, HitroService::class.java))
}
If you want to start a service and it should run in background use START_STICKY in your corresponding service.
You can start service with on boot also,
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
And create receiver,
<receiver android:name=".auth.NotificationBroadcast" android:enabled="true" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
In Brodcast Receiver add,
#Override
public void onReceive(Context context, Intent intent) {
System.out.println("BroadcastReceiverBroadcast--------------------ReceiverBroadcastReceiverBroadcastReceiver----------------BroadcastReceiver");
if (intent != null) {
String action = intent.getAction();
switch (action) {
case Intent.ACTION_BOOT_COMPLETED:
System.out.println("Called on REBOOT");
// start a new service
startService(new Intent(getApplicationContext(),Servicename.class));
break;
default:
break;
}
}
}
And your service is like,