Calling an activity method from a JobIntentService - java

I would like to call a non-static method in the for-loop inside the onHandleWork. How can I achieve that?
#Override
protected void onHandleWork(#NonNull Intent intent) {
Log.d(TAG, "onHandleWork");
String input = intent.getStringExtra("inputExtra");
for (int i = 0; i < 10; i++) {
Log.d(TAG, input + " - " + i);
new MainActivity.method();
if (isStopped()) return;
SystemClock.sleep(1000);
}
}

You should broadcast a message that the activity is listening instead.
To achieve that, use a broadcastreceiver on the activity and send It from the job service with context.sendBroadcast(intent)
You can make your activity listening by declaring a broadcastreceiver programatically or in the AndroidManifest.xml file. Note that If you declare it programatically, the activity Will only receive the broadcast If It is opened. If you use the manifest approach, when you activity is not opened and you send a broadcast, the sustém os going to start your activity
Receiving Broadcasts:
https://developer.android.com/guide/components/broadcasts.html#manifest-declared-receivers
Sending Broadcasts:
https://developer.android.com/guide/components/broadcasts.html#sending-broadcasts
Docs:
https://developer.android.com/reference/android/content/BroadcastReceiver

Related

Android using broadcastReceiver, but when I force close the app, I don't get anything in the Activity

Not sure how to get the receiver to work on the activity once the app is forced closed.
What am I missing to get this to work even if the app was forced closed? Any help would be appreciated.
I am getting the BroadcastReceiver service to work, Just not getting anything to pick up on the activity level.
I have my receiver (Service):
public class MyReceiver extends BroadcastReceiver {
public static final String SEND_NOTIFICATION_ACTION = "com.clover.sdk.app.intent.action.APP_NOTIFICATION";
#Override
public void onReceive(Context context, Intent intent) {
Log.i("MyReceiver", "Triggered MyReceiver");
String action = intent.getAction();
Bundle getIntent = intent.getExtras();
if (action.equals(SEND_NOTIFICATION_ACTION)) {
Log.i("MyReceiver Gotten", "Found");
intent = new Intent("broadCastName");
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("orderId", getIntent.getString("payload"));
Log.i("Receiver OrderID", getIntent.getString("payload"));
context.sendBroadcast(intent);
}
}
}
My Activity
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
registerReceiver(broadcastReceiver, new IntentFilter("broadCastName"));
}
}
Then my broadcastReceiver in my activity:
// Add this inside your class
BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Log.i("MyReceiver Gotten 2", "Found");
Bundle b = intent.getExtras();
Log.i("MyReceiver Gotten 3", b.getString("orderId"));
new SpecificOrderAsyncTask(MainActivity.this).execute(b.getString("orderId"));
}
};
Not sure how to get the receiver to work on the activity once the app is forced closed. What am I missing to get this to work even if the app was forced closed?
That's contradictory - you can't get a receiver to work in an Activity that registered it at runtime if that Activity that is hosting the receiver is killed. When you force close, every in the app process - including the Activity and the receiver you registered with it - disappears.
The point of calling registerReceiver is to listen for broadcasts only during a specific time frame or lifecycle.
If you want the receiver to work even when the app is closed, don't register it at runtime - register it in the manifest.
Simple,
Registering service in an activity is temporary, registering service in a manifest will run even after closing the application.
But the broadcast you use is a simple message transfer system, that won't work even after you register in manifest and close the application. You have to create a background service that runs always in background in android system and should awake listening to some events passed.

Disappearing string in intent

I have something strange going on with my application.
I am trying to send a string via Broadcast by doing the following:
1st step (Sending):
Intent intent = new Intent("INFO");
intent.putExtra("INFO_VALUE", "hello_world_2019");
2nd step (Receiving):
if ("INFO".equals(intent.getAction())) {
String abc = intent.getStringExtra("INFO_VALUE");
Log.i(TAG, "" + abc);
}
Doing the previous steps, I get a null into my abc field. Also, if I use the debugger and check my intent related to the second step, I get:
intent -> mExtras -> mMap -> value[0] -> name: "hello_world_2019"
I am confused to what is going on. The abc field is not supposed to be null, but it is in this case.
How can I populate the aforementioned field so it is not null ?
Please explain what exactly you are trying to do, if you want to send data from one activity to other than my friend this is not the correct way to do that.
If you want to send a broadcast and receive that somewhere inside your code than you need to follow the below steps:
ReceiverActivity.java
#Override
public void onCreate(Bundle savedInstanceState) {
...
// Register to receive messages.
// We are registering an observer (mMessageReceiver) to receive Intents
// with actions named "custom-event-name".
LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver,
new IntentFilter("INFO"));
}
// Our handler for received Intents. This will be called whenever an Intent
// with an action named "custom-event-name" is broadcasted.
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// Get extra data included in the Intent
String message = intent.getStringExtra("message");
Log.d("receiver", "Got message: " + message);
}
};
#Override
protected void onDestroy() {
// Unregister since the activity is about to be closed.
LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
super.onDestroy();
}
SenderActivity.java
private void sendMessage() {
Log.d("sender", "Broadcasting message");
Intent intent = new Intent("INFO");
// You can also include some extra data.
intent.putExtra("message", "Message goes here!");
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}

Sending data between one Thread and two Activities in android

I have a thread that listens for an inputStream and can send some data with some ouputStream that I got from a Bluetooth socket.
Here is what I'm trying to achieve: I have a MainActvity And Activity B. I need to have both to be capable to receive data from the Thread or send data to the Thread.
I can't just make a new instance of my thread cause it's going to cut the connection.
I'm a new to android and programming so it's very hard to know what I really need.
I tried my best with handlers, Broadcast receiver but had no luck for making it work in Activity B.
Whatever may work for my case. It would be nice having an example of it.
You can use a LocalBroadcastManager in a Service which runs your Thread and let the Activities register receivers on it.
In your Activity:
final LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(getApplicationContext());
final IntentFilter filter = new IntentFilter();
filter.addAction("SAMPLE_ACTION");
lbm.registerReceiver(new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG, "onReceive() called with: context = [" + context + "], intent = [" + intent + "]");
}
}, filter);
In your Service
final LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(getApplicationContext());
final Intent intent = new Intent("SAMPLE_ACTION");
lbm.sendBroadcast(intent);

Why calling a class that extends Activity does not work when called from one that extends Plugin?

I have a java Class that extends Plugin (PhoneGap), but when inside this class, i call another class that extends Activity, it just doesn't work !. i mean, it seems like it doesn't get called. To confirm this, i have change my second class, this time, not extending from Activity and it works fine. i need teh second one to extends from Activity because i am using this two utilities (getFileStreamPath and openFileOutput) to create a file
File filepath = getFileStreamPath("filename.CPCL"); and openFileOutput
FileOutputStream os = this.openFileOutput(fileName, Context.MODE_PRIVATE);
I have an app with a class which extends a custom Service that calls another class which extends Activity.
First I instantiate the Activity. In the onCreate of your Plugin class use:
// get a handle on your Application
Application app = getApplication();
Intent intent = new Intent(getApplicationContext(), YourActivity.class);
app.startActivity(intent);
This will start your Activity and call the standard Lifecycle events.
The way I handle continued communication with the running Activity is by using a Handler to send a broadcast from your plugin which the Activity picks up in its receiver. In the onCreate of your plugin:
mHandler.post(new Runnable() {
#Override
public void run() {
Log.d(TAG, "Call the Activity");
Intent intent = new Intent(YourActivity.CALL_FROM_PLUGIN);
intent.putExtra("request", <<Any extras you might want to send through>>);
sendBroadcast(intent);
}
});
In the Activity I declare the variable:
public static final String CALL_FROM_PLUGIN= "CALL_FROM_PLUGIN";
then in onCreate() I added the following;
IntentFilter filter = new IntentFilter();
filter.addAction(CALL_FROM_PLUGIN);
registerReceiver(mBroadcastReceiver, filter);
and then implemented a BroadcastReceiver:
BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Log.d(TAG, "BroadcastReceiver.onReceive()");
if (CALL_FROM_PLUGIN.equals(action)) {
Log.d(TAG, "Received call from Plugin");
// DO YOUR STUFF HERE
}
}
};
Someone else might be able to point out why this is necessary from a framework point of view, but this is the way I understand that Activities should be called. I hope this applies to your plugin class the way it does with my service class!

How to close an activity (finish()) from service?

i make a lock screen application.. i have some service that listen to the SMS.. when the SMS receiving command andro-lock then i display a lock screen that called by service:
here'e the service's code :
if (tempMessage[0].toString().equalsIgnoreCase("andro-lock") && tempMessage[1].toString().equals(tempPassword.toString()))
{
//Toast.makeText(ListenSMSservice.this, "Menjalankan command andro-lock", Toast.LENGTH_LONG).show();
openDatabase();
updateStatusL();
Intent myIntent = new Intent(ListenSMSservice.this,LockScreenForm.class);
myIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getApplication().startActivity(myIntent);
}
that code has works perfecly, but i have some problem when i try to unlock my phone.. if my service receive command andro-unlock then i must close (finish) that lockscreen.java.. i was trying many code and still not works.. what must i do to close the lockscreen activity when my service receiving command andro-unlock?? please help..
else if (tempMessage[0].toString().equalsIgnoreCase("andro-unlock") && tempMessage[1].toString().equals(tempPassword.toString()))
{
//what must i do??
//any solution??
}
Thanks for your help..
A possible solution to stop the activity would be:
Intent myIntent = new Intent(ListenSMSservice.this,LockScreenForm.class);
myIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Bundle myKillerBundle = new Bundle();
myKillerBundle.putInt("kill",1);
myIntent.putExtras(myKillerBundle);
getApplication().startActivity(myIntent);
In LockScreenForm
onCreate(Bundle bundle){
if(this.getIntent().getExtras().getInt("kill")==1)
finish();
}
You could send an intent to your activity with an extra, and the activity could read this extra and, if present, finish() itself.
Regards,
Stéphane

Categories

Resources