I have a timer but I want it to also run in the background, I created a new Service, I think it works but I have a problem with it, I want also to change the layout attributes, like changing TextView text using setText method, I prefer doing it with BroadCastReceiver so I have the following code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.textView);
IntentFilter filter = new IntentFilter();
filter.addAction("SOME_ACTION");
receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
textView.setText("hey");
}
};
registerReceiver(receiver, filter);
buttonStart = (Button) findViewById(R.id.start);
buttonStart.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startService(new Intent(MainActivity.this, LocalService.class));
}
});
}
#Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(receiver);
}
I registered here the Receiver so it will happen when I am broadcasting from the Service and change the text to "hey" - I wanted it just to check if the broadcast is working. on the Service I used a code that runs a timer and when it start it will broadcast the message, it is the first time I am using broadcasting receiver for sending actions and not just to wait until Bluetooth is on and stuff like this, here is my Service code:
public class LocalService extends Service
{
private static Timer timer = new Timer();
public IBinder onBind(Intent arg0)
{
return null;
}
public void onCreate()
{
super.onCreate();
startService();
}
private void startService()
{
timer.scheduleAtFixedRate(new mainTask(), 0, 5000);
}
private class mainTask extends TimerTask
{
public void run()
{
Intent intent = new Intent();
intent.setAction("SOME_ACTION");
sendBroadcast(intent);
}
}
public void onDestroy()
{
super.onDestroy();
}
}
Thanks for helping.
Related
I'm working on an Android app in which I need to detect when user locked and unlocked, not the screen on/off. So, that I can perform certain action according locked and unlocked. But I'm unable to achieve my goal.
I declare a broadcast inside a service, register the service and receiver inside the manifest and also actions.
It's working fine, when app is open. As the app goes in background it's stop working.
public class UseService extends Service {
#Nullable
Vibrator vibr;
MediaPlayer audi;
//This is Service Class
#Override
public IBinder onBind(Intent intent) {
return null;
}
public void onCreate() {
super.onCreate();
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_SCREEN_OFF);
filter.addAction(Intent.ACTION_SCREEN_ON);
filter.addAction("android.intent.action.SCREEN_ON");
registerReceiver(receiver, filter);
}
//Broadcast Receiver
private final BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
KeyguardManager myKM = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE);
if (action.equals(Intent.ACTION_SCREEN_OFF) && myKM.inKeyguardRestrictedInputMode())
{
vibr.vibrate(500);
if( action.equals(Intent.ACTION_SCREEN_ON) && !myKM.inKeyguardRestrictedInputMode() )
{
vibr.vibrate(5000);
}
}
}
};
//************************Started*************
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
audi=MediaPlayer.create(UseService.this, R.raw.start);
Toast.makeText(UseService.this, "The Service Has Been Started",Toast.LENGTH_SHORT).show();
return START_STICKY;
}
//*******************OnDestroy****************
#Override
public void onDestroy() {
Toast.makeText(UseService.this, "The Service is Destroyed",Toast.LENGTH_SHORT).show();
unregisterReceiver(receiver);
}
}
Main Activity
public class MainActivity extends AppCompatActivity {
Vibrator vibr;
Button btns;
//this is MainActivity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btns=(Button)findViewById(R.id.btn);
vibr=(Vibrator) getSystemService(VIBRATOR_SERVICE);
btns.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent(getApplicationContext(), UseService.class);
startService(intent);
}
});
}
#Override
protected void onPause() {
super.onPause();
}
}
myButton is a button that when clicked is supposed to receive a broadcast from a background IntentService. But the broadcast is never received. However if I move the broadcastReceiver outside of myButton.setOnClickListener function, then I begin to receive broadcasts from my background service.
Is there a way to make the broadcastReceiver receive broadcasts within the setOnClickListener function?
public class MainActivity extends Activity {
private BroadcastReceiver broadcastReceiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
myButton = (Button)findViewById(R.id.button1);
myButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context arg0, Intent intent) {
Toast.makeText(MainActivity.this, "BROADCAST RECEIVED", Toast.LENGTH_SHORT).show();
stopService(msgIntent);
}
};
}
});
public void onResume()
{
super.onResume();
IntentFilter filter = new IntentFilter(SimpleIntentService.ACTION_RESP);
filter.addCategory(Intent.CATEGORY_DEFAULT);
registerReceiver(broadcastReceiver,filter);
}
public void onPause()
{
unregisterReceiver(broadcastReceiver);
super.onPause();
}
}
I had to take out the broadcastReceiver from onClick method. This works and broadcast is received:
public class MainActivity extends Activity {
private BroadcastReceiver broadcastReceiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
myButton = (Button)findViewById(R.id.button1);
myButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
//do extra stuff
}
});
broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context arg0, Intent intent) {
Toast.makeText(MainActivity.this, "BROADCAST RECEIVED", Toast.LENGTH_SHORT).show();
stopService(msgIntent);
}
};
}
}
Do you forget to registerReceiver?
You might also need to assign a IntentFilter when you register a receiver.
The following is some sample codes from my project:
private class LocationInfoReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// do something
}
}
locationInfoReceiver = new LocationInfoReceiver();
// the key you use setAction() method in your Intent Service
IntentFilter locationInfoReceiverFilter = new IntentFilter("your key");
locationInfoReceiverFilter.addCategory(Intent.CATEGORY_DEFAULT);
registerReceiver(locationInfoReceiver, locationInfoReceiverFilter);
How can I use AlarmManager to call a specific method of an Activity, in my case I need to stop a service by calling KillMyServer method of my Activity 2 hours later from know.
I can't use Timer or postDelayed, because if an app goes to background Android may close it after a while, but AlarmManager will survive.
why to use Alarm here? you can stop service by calling stopself() method on Service.
public class MyService extends Service {
public static final String ACTION_START_TIMER = "com.sample.myapp.action.ACTION_START_TIMER";
private TimerReceiver receiver;
#Override
public void onCreate() {
super.onCreate();
receiver = new TimerReceiver();
IntentFilter filter = new IntentFilter(ACTION_START_TIMER);
registerReceiver(receiver, filter);
}
public void runKillTimer() {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
stopSelf();
}
}, 2 * 60 * 60 * 1000);
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(receiver);
}
private class TimerReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
runKillTimer();
}
}
}
public class MyActivity extends Activity {
#Override
protected void onStop() {
super.onStop();
Intent intent = new Intent(MyService.ACTION_START_TIMER);
sendBroadcast(intent);
}
}
I have a service and an activity that communicate.
When I click the button(I have galaxy s3 there is only one button) then my activity of course disapear and my service is keep running but if I click the back (touch) button then my service is destroyed.
How can I change that?I want the service to keep running untill the activity destroys it.
EDIT
Here is the code:
Service:
public class MyService extends Service
{
private static final String TAG = "BroadcastService";
public static final String BROADCAST_ACTION = "com.websmithing.broadcasttest.displayevent";
private final Handler handler = new Handler();
private Intent intent;
int counter = 0;
#Override
public void onCreate()
{
super.onCreate();
intent = new Intent(BROADCAST_ACTION);
}
#Override
public void onStart(Intent intent, int startId)
{
// handler.removeCallbacks(sendUpdatesToUI);
handler.postDelayed(sendUpdatesToUI, 1000); // 1 second
}
private Runnable sendUpdatesToUI = new Runnable() {
public void run() {
DisplayLoggingInfo();
handler.postDelayed(this, 1000); // 10 seconds
}
};
private void DisplayLoggingInfo() {
intent.putExtra("counter", String.valueOf(++counter));
sendBroadcast(intent);
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onDestroy() {
handler.removeCallbacks(sendUpdatesToUI);
super.onDestroy();
}
}
Activity:
public class MainActivity extends Activity {
private static final String TAG = "BroadcastTest";
private Intent intent;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
intent = new Intent(this, MyService.class);
startService(intent);
registerReceiver(broadcastReceiver, new IntentFilter(MyService.BROADCAST_ACTION));
}
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
updateUI(intent);
}
};
#Override
public void onDestroy() {
super.onPause();
unregisterReceiver(broadcastReceiver);
stopService(intent);
}
private void updateUI(Intent intent)
{
String counter = intent.getStringExtra("counter");
Log.d(TAG, counter);
TextView txtCounter = (TextView) findViewById(R.id.textView1);
txtCounter.setText(counter);
}
}
you can put your app in the background instead off finishing it.
#Override
public void onBackPressed() {
moveTaskToBack(true);
// super.onBackPressed();
}
Ofcourse your service stops, when you press the back button. The back button most calls finish() on the activity, and it is destroyed. When you press the other button (the home button), it just minimizes your app, and it will be only destroyed later, when the OS wants to free up space.
If you want to keep your service running, make it a foreground service, and dont stop it on activity destroy.
I am trying to register a broadcastreceiver in a small Android app that I am playing around with. I think I am doing what I am supposed to do, but still the receiver doesn't register. It must be something small that I am missing and it is driving me crazy.
public class CreateReceiver extends Activity
{
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}//end of onCreate
BroadcastReceiver myreceiver = new BroadcastReceiver()
{
#Override
public void onReceive(Context recvc, Intent recvi)
{
}
};
#Override
public void onResume()
{
super.onResume();
IntentFilter intentFilter = new IntentFilter(Intent.ACTION_CAMERA_BUTTON);
if (this.registerReceiver(myreceiver, intentFilter) == null)
{
Toast.makeText(this, "Could not register receiver", Toast.LENGTH_LONG).show();
}//end of if
}//end of onResume
#Override
public void onPause()
{
this.unregisterReceiver(myreceiver);
super.onPause();
}//end of onPause
}//end of CreateReceiver
Can anyone tell me what I am doing wrong? Thanks.
You have to register your BroadcastReceiver from within onCreate
public class CreateReceiver extends Activity
{
private IntentFilter intentFilter = new IntentFilter(Intent.ACTION_CAMERA_BUTTON);
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
registerReceiver(myreceiver , intentFilter);
}//end of onCreate
BroadcastReceiver myreceiver = new BroadcastReceiver()
{
#Override
public void onReceive(Context recvc, Intent recvi)
{
}
};
...