I have a class which doesn't extend Activity or Fragment. It is a independent class. I would like to use that class to control an Activity start and finish.
public class MyActivityManager() {
public MyActivityManager(Context context) {
mContext = context;
}
public void startMainActivity() {
Intent intent = new Intent(mContext, MainActivity.class);
mContext.startActivity(intent);
}
public void closeMainActivity() {
// how can I close the started main activity from the other function here?
}
}
As you can see, I started MainActivity from one function, and in another function, I would like to close the MainActivity started. But how can I have a reference to the started MainActivity?
(My main purpose is to let upper caller to use this MyActivityManager to start and close MainActivity)
If the current way is not possible, how to achieve what I want?
//Try the below code and let me know if any issues.
package com.example.raghavendrapai.myapplication;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
registerReceiver(mCloseReceiver, new IntentFilter("close_main_activity"));
}
#Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(mCloseReceiver);
}
private BroadcastReceiver mCloseReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("close_main_activity")) {
finish();
}
}
};
}
// And in your class
package com.example.raghavendrapai.myapplication;
import android.content.Context;
import android.content.Intent;
/**
* Created by raghavendra.pai on 08/03/18.
*/
public class MyActivityManager {
private Context mContext;
public MyActivityManager(Context context) {
mContext = context;
}
public void startMainActivity() {
Intent intent = new Intent(mContext, MainActivity.class);
mContext.startActivity(intent);
}
public void closeMainActivity() {
Intent intent = new Intent("close_main_activity");
mContext.sendBroadcast(intent);
}
}
Related
I am sending a broadcast from App A to App B and I am already receiving it in app B. After receiving the broadcast I want to bring the App B to the front. How can I bring the App B to the front after receiving the broadcast from the App A?
package com.mysender;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Intent intent=new Intent();
intent.setAction("com.mysender.Data");
intent.putExtra("path", "/Download/income_tax_return.pdf");
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
sendBroadcast(intent);
}
}
In the App B I am doing the following in the MainActivity:
package com.example.app;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.widget.Toast;
public class MainActivity extends Activity {
private WebView mWebView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Receive broad Cast fromn External App
IntentFilter filter = new IntentFilter("com.mysender.Data");
registerReceiver(myReceiver, filter);
}
private MyReceiver myReceiver =new MyReceiver(){
#Override
public void onReceive(Context context, Intent intent) {
String path = intent.getStringExtra("path");
Toast.makeText(context,"Data Received from External App: " + path, Toast.LENGTH_SHORT).show();
}
};
#Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(myReceiver);
}
}
Trust me I have spent so much time searching for solutions but it doesnt seem to work for me. I have a really simple code where i would like my phone to discover bluetooth devices (yet). Here is the code (processing).
import android.app.Application;
import android.app.Activity;
import android.os.Bundle;
import android.content.IntentFilter;
import android.content.Intent;
import android.content.Context;
import android.content.BroadcastReceiver;
import java.util.Set;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
BluetoothAdapter BT = BluetoothAdapter.getDefaultAdapter();
Set<BluetoothDevice> pairedDevices = BT.getBondedDevices();
BroadcastReceiver BCR = new BroadcastReceiver2();
void setup(){
BT.enable();
registerReceiver(BCR, new IntentFilter(BluetoothDevice.ACTION_FOUND));
if(!BT.isDiscovering()) BT.startDiscovery();
}
void draw(){
//
}
public class BroadcastReceiver2 extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent){
disDevName = intent.getStringExtra(BluetoothDevice.EXTRA_NAME);
print("Discovered: ");
println(disDevName);
if(disDevName == "XCHAN_PC") BTFound = true;
}
}
Here is the error:
The function "registerReceiver(BroadcastReceiver, IntentFilter)" does not exist
This is because PApplet has no registerReceiver method but instead, in Context. But I do not know how to get the context. I tried puting this code:
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
}
and get the context out using this:
MainActivity act = new MainActivity();
con = act.getApplicationContext();
//...
//then this
con.registerReceiver(BCR, new IntentFilter(BluetoothDevice.ACTION_FOUND));
of it but it would say "Null Context".
Any help would be very appreciated.
try this
In your Activity class:
public class MyActivity extends Activity {
private MyClass myClass = null; //MyClass is your bluetooth utility class
#Override
public void onResume(Bundle savedInstanceState) {
super.onResume(savedInstanceState);
// ...pass context
myClass = new MyClass(this);
}
#Override
public void onPause() {
if (myClass != null) {
myClass.unregisterReceiver(this);
myClass = null;
}
super.onPause();
}
}
Now in your MyClass use:
public class MyClass {
private BroadcastReceiver myReceiver = null;
public MyClass(Context context) {
myReceiver = new MyBroadcastReceiver();
context.registerReceiver(myReceiver, new IntentFilter(
BluetoothDevice.ACTION_ACL_CONNECTED));
context.registerReceiver(myReceiver, new IntentFilter(
BluetoothDevice.ACTION_ACL_DISCONNECTED));
context.registerReceiver(myReceiver, new IntentFilter(
BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED));
}
public void unregisterReceiver(Context context) {
context.unregisterReceiver(this);
}
}
public class MyBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) {
// do some stuff
}
}
}
I like to exit my application immediately after starting a service.
The code below causes the activity to finish before the service is started.
How do I set a listener to prompt me when the service is started?
btn = (ImageButton) findViewById(R.id.button );
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startService(new Intent(MainActivity.this, MyService.class));
//I want to exit the activity here.
finish(); // this exits the activity before the service is started
}
});
The following are the codes I used, based on the proposal by #Er.Arjunsaini
on the ACTIVITY file, I register to listen for an "Exit App" broadcast.
private final BroadcastReceiver exitAppReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
//activity exits when "exit app" broadcast received.
finish();
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//REGISTER TO LISTEN FOR THE BROADCAST
LocalBroadcastManager.getInstance(this).
registerReceiver(exitAppReceiver, new IntentFilter(getString(R.string.exit_app)));
btn = (ImageButton) findViewById(R.id.my_button);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startService( new Intent(this, MyService.class));
}
});
}
#Override
public void onDestroy() {
//UNREGISTER THE RECEIVER
LocalBroadcastManager.getInstance(this).
unregisterReceiver(exitFloatingWindowReceiver);
super.onDestroy();
}
on the SERVICE file, I send an "Exit APP" broadcast.
#Override
public void onCreate() {
super.onCreate();
//... do the rest of the Service initializing
//CLOSE ACTIVITY
LocalBroadcastManager.getInstance(this).
sendBroadcast(new Intent(getString(R.string.exit_app)));
}
check out ServiceConnection, onServiceConnected may be method you are looking for to call finish()
HERE you have example
If you use bindService() instead of startService(), you can use the Message based communication system between Activity and Service.
This is explained in this reference.
At the end of the section there's a link to sample classes:
-MessengerService.java
-MessengerServiceActivities.java
Here an example of an Activity with 2 button, one for starting the Service and one for sending a message to the Service that will resend a message to the Activity to close it.
MainActivity.java
package com.pasquapp.brodcasttest01;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.view.View;
import android.widget.Button;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
public final static int WHAT_CLOSE_ACTIVITY=1;
private Button startServiceButton;
private Button closeButton;
private Messenger activityMessenger;
private Messenger serviceMessenger;
private MyServiceConnection serviceConnection;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
activityMessenger =new Messenger(new ActivityHandler());
initView();
}
#Override
protected void onDestroy() {
super.onDestroy();
if(serviceConnection!=null)
unbindService(serviceConnection);
}
private void initView(){
startServiceButton=findViewById(R.id.button_start_service);
startServiceButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startService();
}
});
closeButton=findViewById(R.id.button_close);
closeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(serviceMessenger!=null){
Message msg=Message.obtain();
msg.replyTo=activityMessenger;
msg.what=MyService.WHAT_CLOSE_ACTIVITY;
try {
serviceMessenger.send(msg);
} catch (RemoteException e) {
e.printStackTrace();
}
}
}
});
}
private class MyServiceConnection implements ServiceConnection{
#Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
serviceMessenger=new Messenger(iBinder);
}
#Override
public void onServiceDisconnected(ComponentName componentName) {
serviceMessenger=null;
}
}
private void startService(){
serviceConnection=new MyServiceConnection();
bindService(new Intent(this,MyService.class),serviceConnection,BIND_AUTO_CREATE);
}
private class ActivityHandler extends Handler{
#Override
public void handleMessage(#NonNull Message msg) {
int what=msg.what;
switch (what){
case WHAT_CLOSE_ACTIVITY:
MainActivity.this.finish();
break;
default:
super.handleMessage(msg);
}
}
}}
MyService.java
package com.pasquapp.brodcasttest01;
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import androidx.annotation.NonNull;
public class MyService extends Service {
public static final int WHAT_CLOSE_ACTIVITY=1;
private Messenger mMessenger;
public MyService() {
}
#Override
public void onCreate() {
super.onCreate();
mMessenger=new Messenger(new ServiceHandler());
}
#Override
public IBinder onBind(Intent intent) {
return mMessenger.getBinder();
}
private class ServiceHandler extends Handler{
#Override
public void handleMessage(#NonNull Message msg) {
int what=msg.what;
switch (what){
case WHAT_CLOSE_ACTIVITY:
Messenger messenger=msg.replyTo;
Message closeMsg=Message.obtain();
closeMsg.what=MainActivity.WHAT_CLOSE_ACTIVITY;
try {
messenger.send(closeMsg);
} catch (RemoteException e) {
e.printStackTrace();
}
break;
default:
super.handleMessage(msg);
}
}
}
}
/* This is my launcher activity basically a splash screen which will wait for 5 sec but there is some problem with the intent..pls help
*/
package com.hfad.practice;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
public class Starting extends AppCompatActivity {
public void start()
{
}
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_starting);
Thread timer=new Thread()
{
public void run()
{
try
{
sleep(5000);
}
catch(InterruptedException e)
{
e.printStackTrace();
}
finally
{
Intent intent=new Intent(this,MainActivity.class); /*
here it is showing an error thats mentioned in the title*/
startActivity(intent);
}
}
};
timer.start();
}
}
Change
Intent intent=new Intent(this,MainActivity.class);
with
Intent intent=new Intent(Starting.this,MainActivity.class);
in your case this refers to the Thread subclass, while the first argument of Intent is a Context object
I have a broadcast receiver in my app which is fired every time the user gets an incoming call. Now, when it happens, I need the broadcast receiver to invoke a specific method in a specific activity. Now, I tried to make this method static and therefore available, but something tells me it is a very bad idea.
Accordingly, I tried to instantiate the broadcast receiver inside my activity without declaring it in my manifest but the problem is - when the app is off, the activity dosn't exist and therefore I can't invoke my method.
So my question is - How can I invoke this method when the broadcast receiver is fired up, without making it "public static"?
Here is my activity code(I have deleted the irrelevant parts)
package com.silverfix.ringo.activities;
import com.silverfix.ringo.R;
import com.silverfix.ringo.activities.fragments.DataManagerFragment;
import android.app.ActionBar;
import android.app.Activity;
import android.app.FragmentTransaction;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
public class RingtonesActivity extends Activity{
private DataManagerFragment dataManagerFragment;
private IntentFilter filter;
private BroadcastReceiver phoneCall;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ringtones);
ActionBar ab = getActionBar();
ab.setDisplayShowTitleEnabled(false);
ab.setDisplayHomeAsUpEnabled(true);
dataManagerFragment = new DataManagerFragment();
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.add(dataManagerFragment, "DataManagerFragment");
ft.commit();
filter = new IntentFilter();
filter.addAction("android.intent.action.PHONE_STATE");
phoneCall = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
dataManagerFragment.act();
}
};
registerReceiver(phoneCall, filter);
}
}
You can use observers , like
public class MyReceiver extends BroadcastReceiver {
public MyReceiver() {
}
#Override
public void onReceive(Context context, Intent intent) {
ObservableObject.getInstance().updateValue(intent);
}
}
public class MainActivity extends Activity implements Observer {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ObservableObject.getInstance().addObserver(this);
}
#Override
public void update(Observable observable, Object data) {
Toast.makeText(this, String.valueOf("activity observer " + data), Toast.LENGTH_SHORT).show();
}
}
public class ObservableObject extends Observable {
private static ObservableObject instance = new ObservableObject();
public static ObservableObject getInstance() {
return instance;
}
private ObservableObject() {
}
public void updateValue(Object data) {
synchronized (this) {
setChanged();
notifyObservers(data);
}
}
}
Receiver can be used via manifest.
ObservableObject - must be singleton.
This might help: how can I notify a running activity from a broadcast receiver?
Also, you can try using Observers
Something like:
public class BroadcastObserver extends Observable {
private void triggerObservers() {
setChanged();
notifyObservers();
}
public void change() {
triggerObservers();
}
}
In your broadcast receiver:
#Override
public void onReceive(Context context, Intent intent) {
BroadcastObserver bco = new BroadcastObserver();
bco.change();
}
and the Activity:
public class YourActivity extends Activity implements
Observer {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
BroadcastObserver bco = new BroadcastObserver();
bco.addObserver(this);
}
#Override
public void update() {
//TODO: call your desired function
}
}
If anyone needs two-way communication between a BroadcastReceiver and a Activity, I wrote this utility class which simplifies invoking Methods on each other while still being memory-safe.
https://gist.github.com/Jenjen1324/4a0c03beff827082cb641fc8fe2c4e71