Partial Lock for BroadcastReceiver? - java

I have an Activity , that initiates an IntentService to get some work done . When the work is done , the IntentService broadcast's and announces success.
The broadcast receiver is inside the same activity that initiates the IntentService.
The psuedo of this situation
Activity A
{
private BroadcastReceiver receiver = new BroadcastReceiver()
{
#override
public void onReceive(Context context, Intent intent)
{
//handle
}
}
protected void onCreate(Bundle savedInstanceState)
{
//initiate IntentService
}
}
IntentService
{
//Launch spaceshuttle . and broadcast success
}
Now what happens is that sometimes the launching the spaceshuttle takes some times , and the cellphone goes to sleep. As a result of which the broadcast receiver i believe needs to acquire a partial lock perhaps as far as I understand .
But the exact technique to do so has been evading me .
Please help .

The simplest solutions are either for you to:
Use my WakefulIntentService, or
Use the WakefulBroadcastReceiver from the Android Support package
Both will manage the WakeLock for you. My WakefulIntentService is probably a more natural fit for the code as you have shown it, but both should work.

Related

Notification Listener - onNotificationPosted doesn't work

I'have tried all kind of solutions and code but any of this solutions worked for me, and I don't know why. Please help me.
My MainActivity code is:
if(isNotificationServiceEnabled())
{
Intent i= new Intent(this,NotificationsService.class);
i.putExtra("command", "get_status");
startService(i);
}
else
startActivity(new Intent(Settings.ACTION_NOTIFICATION_LISTENER_SETTINGS));
Now I'm just tryng to check if the service read a nostification posted, but from log i can only see that it enters in onCreate method but no in onNotificationPosted.
This is the code for my service class:
public class NotificationsService extends NotificationListenerService {
#Override
public void onListenerConnected(){
Log.d(TAG, "Connected");
}
#Override
public void onNotificationPosted(final StatusBarNotification sbn){
Log.d(TAG,"got it");
}
I have tried also solutions with broadcast service , but it still doesn't work.
Thanks.
I have found the solutions. In my code I had some problems, but then I tested other code about notification listener in an other project, and It worked. So then I modify my code and now it works.
About notification lisener You don't need to launch the service, because when you launch the app the service is launched. So I just made this changes to my code:
Main
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(!isNotificationServiceEnabled())
{
startActivity(new Intent(Settings.ACTION_NOTIFICATION_LISTENER_SETTINGS));
}
}
#Override
protected void onDestroy() {
super.onDestroy();
}
And in the service I just put the log code to write in debug the notification package.
Instead I got that broadcast are just used to exchange the data between service and my activity, for example to write the notifications in a textview.

Add data to recyclerView from Sqlite in realtime?

I've made an app that is receiving some data from a TCP Client to my TCP Server that store the data in SQlite DB, and actually i've made a recyclerView where to visualize all that data but now my issue is what i'm trying like 2 weeks to refresh the recyclerView in real Time, i mean if a TCP Client will send a new package to my TCP Server and if i'm in the activity with the recyclerView the data have to be added dynamically.
I will also accept any type of tips and suggestions on how to improve my app.
Actually it's my 1st app i've ever created in Android.
HERE you can find my Server(TCPServer),RecyclerViewAdapter,Adapter(constructor),allert.java(class where i invoke the RecyclerViewAdapter.
Hope someone will be able to help me and ill be very grateful.
Try sending broadcast method. Here are the steps :
Make a inner class that extends BroadcastReceiver in your activity.
private class ExampleBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
//do stuffs here, e.g. getting extras from intent
}
Declare a instance of the class outside any methods.
public class MainActivity extends AppCompatActivity {
private ExampleBroadcastReceiver exampleBroadcastReceiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
//stuffs
}
}
Override onResume method. Initialize the instance you just made in this method. Then, register it with a intent-filter. This will make sure that your broadcast receiver ready when user open the activity.
#Override
protected void onResume() {
super.onResume();
IntentFilter filter = new IntentFilter();
filter.addAction("com.example.MainActivity");
exampleBroadcastReceiver = new ExampleBroadcastReceiver();
LocalBroadcastManager.getInstance(this).registerReceiver(exampleBroadcastReceiver, filter);
}
Override onPause method and unregister your receiver.
#Override
protected void onPause() {
super.onPause();
try {
LocalBroadcastManager.getInstance(this).unregisterReceiver(exampleBroadcastReceiver);
} catch (IllegalArgumentException e) {
if (!e.getMessage().contains("Receiver not registered")) {
// unexpected, re-throw
throw e;
}
Make sure you use ArrayList for dynamic data.
Whenever you receive data from server, after you store them in your database, send a broadcast with extras contains data you want to display in your activity.
EDITED
I registered the receiver using an instance of LocalBroadcastManager.

how to make Main Activity thread affect Second Activity

My MainActivity has a Thread that generates RSA keys and returns the amount of time in milliseconds that it took to generate them.
While I run this Thread, the app goes to a second Activity.
I need the second Activity to receive that time in milliseconds.
As I understand, once you call startActivity(), the parent Activity goes to sleep. So how can I run both simultaneously?
Thanks!
You can use LocalBroadcastReceiver.
public class SecondActivity extends AppCompatActivity {
private BroadcastReceiver mRsaReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
ArrayList<String> rsaList = intent.getStringArrayListExtra("rsaList");
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity);
LocalBroadcastManager.getInstance(this).registerReceiver(mRsaReceiver, new IntentFilter("RSA"));
}
#Override
protected void onDestroy() {
super.onDestroy();
LocalBroadcastManager.getInstance(this).unregisterReceiver(mRsaReceiver);
}
}
From Your rsa thread
Intent rsaIntent = new Intent("RSA");
rsaIntent.putExtra("rsaList", rsaArrayList);
LocalBroadcastManager.getInstance(context).sendBroadcast(rsaIntent);
As I understand, once you startActivity(), the parent activity goes to sleep. So how can I run both simultaneously
You do not. And you do not need to. Since you generate your RSA keys on a separate thread that code should be fully independent from your activities (aside from being started in MainActivity). So all you need to know is when your background task finished - and for that you can use either in-app broadcasts or use Event Bus like GreenRobot's EventBus library or use RxJava.

How do I return data from a GCMListenerService to an Activity using a ResultReceiver?

I have a GCMListenerService that will be used for push notifications from my server to my client. I need this listener to interrupt a thread that is running in the Presenter (my project is structured using the MVP pattern). However, I do not know how to pass a result receiver to the Service because I don't think I can overrride onStartCommand(). The other option would be a LocalBroadCast Manager, but I'd like the message to go through even when the activity is paused, so I don't think a local broadcast manager would work.
create abstract BroadcastReceiver as follows :
public abstract class DataReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
onDataRefresh(intent);
}
protected abstract void onDataRefresh(Intent intent);
}
and use it in the activity as follow:
class Acb extends Activity{
onCreate(){
DataReceiver data = new DataReceiver(
#Override
protected void onMenuItemUpdate(Intent intent) {
});
}
}
whatever the data you passed using sendBroadcast(intent); ,that data you can access here .

I want to create a global MediaPlayer that will keep playing no matter which layout is displayed

Instead of creating one in my menu class, I'd like to create a global one outside of the menu class that I can call to keep the sound playing no matter which activity is started. I'm a noob to java, but I have searched and can't find a solution. Here is my "menu" activity. As you can see my MediaPlayer snd is local so it gets paused when the onPause method gets called.
public class Menu extends Activity{
MediaPlayer snd;
ToggleButton btnSound;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.menu);
snd = MediaPlayer.create(getApplicationContext(), R.raw.bgmusic);
snd.start();
btnSound = (ToggleButton) findViewById(R.id.tglSound);
#Override
protected void onPause() {
super.onPause();
snd.pause();
}
The best way to implement your requirement is using a service. You can start a service while the app is intialised. Inside the service start a mediaplayer and start playing. So evenif you are navigating to next or other activities the media will keep playing. You can also give property to the service when to start ad stop. Isted of pausing or stoping mediaplayer you can just stop the service so that the mediplayer will also stop playing. Hope this link will help you for sure.
The answer to your problem lies in the Android reference:
MediaPlayback
If you want your media to play in the background even when your
application is not onscreen—that is, you want it to continue playing
while the user is interacting with other applications—then you must
start a Service and control the MediaPlayer instance from there. You
should be careful about this setup, because the user and the system
have expectations about how an application running a background
service should interact with the rest of the system. If your
application does not fulfil those expectations, the user may have a
bad experience. This section describes the main issues that you should
be aware of and offers suggestions about how to approach them.
Create a service like this snippet:
public class whatEverYourServiceName extends Service{
#Override
public void onStart(Intent intent, int startId){
super.onStart(intent, startId);
//Add your code here mate
}
#Override
public void onDestroy(){
super.onDestroy();
//Add what do you want to do here when the service is stop like do a backflip
snd.pause();
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
}
Then call it using this
Intent it = new Intent();
it.setAction("your.package.name.whatEverYourServiceName");
startService(it);
Then add this to your manifest
<service
android:name="your.package.name.whatEverYourServiceName"
android:label="Your Service Homie"
android:process=":my_process" >
<intent-filter>
<action android:name="your.package.name.whatEverYourServiceName" >
</action>
</intent-filter>
</service>
To stop the sound just stop the service using this
stopService(new Intent(this, whatEverYourServiceName.class));
Hope it helps.

Categories

Resources