How can i create a broadcast receiver? - java

This is my first time using the stackoverflow
I am creating a chat program but only coding the broadcast receiver and receiving message notification left. I created an exampleapp for my intent but it only works when app is open. How can i simply create a broadcast receiver?
I am not getting error
My MainActivity:
package com.example.backgroundservice;
import android.app.Activity;
import android.os.Bundle;
import android.content.Intent;
import android.widget.Toast;
import com.example.backgroundservice.R;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startService(new Intent(this, BackgroundService.class));
Toast.makeText(this, "Intent Başladı!", Toast.LENGTH_LONG).show();
}
}
(I did not added my other codes because i am getting error and i can not solve because i am coding on android)

My Intent:
import android.app.Service;
import android.content.*;
import android.os.*;
import android.widget.Toast;
public class BackgroundService extends Service {
public Context context = this;
public Handler handler = null;
public static Runnable runnable = null;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
Toast.makeText(this, "Service created!", Toast.LENGTH_LONG).show();
handler = new Handler();
runnable = new Runnable() {
public void run() {
Toast.makeText(context, "Service is still running", Toast.LENGTH_LONG).show();
handler.postDelayed(runnable, 10000);
}
};
handler.postDelayed(runnable, 15000);
}
#Override
public void onDestroy() {
/* IF YOU WANT THIS SERVICE KILLED WITH THE APP THEN UNCOMMENT THE FOLLOWING LINE */
//handler.removeCallbacks(runnable);
Toast.makeText(this, "Service stopped", Toast.LENGTH_LONG).show();
}
#Override
public void onStart(Intent intent, int startid) {
Toast.makeText(this, "Service started by user.", Toast.LENGTH_LONG).show();
}
}```

Related

Android App not responding after music service has started

I have an android app in which I have an activity and a service.
The service is supposed to play music and switch between four songs (depends on what button you press)
The problem is that a few minutes/seconds (it's not always at the same time) after you start the service by playing a song a notification pop ups which claims that the 'app has stopped responding' (with the option to wait and the option to exit). If you press the wait button the notification just goes away and the app and music continues the same. The notification will keep coming back though and unfortunately I am not sure why.
Should probably mention that this only happens to me when the service is on. I have tested this app many times. Never have a notification like that. Only when music is played.
My service:
package com.example.project25112021;
import android.app.Service;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.widget.Toast;
import androidx.annotation.Nullable;
public class MyService extends Service {
MediaPlayer mediaPlayer;
MediaPlayer mediaPlayer2;
MediaPlayer mediaPlayer3;
MediaPlayer mediaPlayer4;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
mediaPlayer = MediaPlayer.create(this, R.raw.stronger);
mediaPlayer.setLooping(true); // Set looping
mediaPlayer.setVolume(100, 100);
mediaPlayer2 = MediaPlayer.create(this, R.raw.silksonic);
mediaPlayer2.setLooping(true); // Set looping
mediaPlayer2.setVolume(100, 100);
mediaPlayer3 = MediaPlayer.create(this, R.raw.davidguetta);
mediaPlayer3.setLooping(true); // Set looping
mediaPlayer3.setVolume(100, 100);
mediaPlayer4 = MediaPlayer.create(this, R.raw.beatit);
mediaPlayer4.setLooping(true); // Set looping
mediaPlayer4.setVolume(100, 100);
}
public int onStartCommand(Intent intent, int flags, int startId) {
int number = intent.getIntExtra("key", 0);
mediaPlayer.start();
mediaPlayer2.start();
mediaPlayer3.start();
mediaPlayer4.start();
mediaPlayer.seekTo(0);
mediaPlayer2.seekTo(0);
mediaPlayer3.seekTo(0);
mediaPlayer4.seekTo(0);
mediaPlayer.pause();
mediaPlayer2.pause();
mediaPlayer3.pause();
mediaPlayer4.pause();
if (number == 0){
mediaPlayer.start();
}
if (number == 1){
mediaPlayer2.start();
}
if (number == 2){
mediaPlayer3.start();
}
if (number == 3){
mediaPlayer4.start();
}
return startId;
}
//public void onStart(Intent intent, int startId) { }
#Override
public void onDestroy() {
mediaPlayer.stop();
mediaPlayer.release();
}
#Override
public void onLowMemory() {
}
}
The activity in which you choose what song to play:
package com.example.project25112021;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
public class SettingsMain extends AppCompatActivity {
Button button;
Button song1;
Button song2;
Button song3;
Button song4;
ImageView album1;
ImageView album2;
ImageView album3;
ImageView album4;
Drawable drawable;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings_main);
drawable = CameraBackground.getInstance().getBitmap();
LinearLayout relative = (LinearLayout) findViewById(R.id.ButtonFinBack);
if(drawable!= null) {
relative.setBackgroundDrawable(drawable);
}
else
relative.setBackgroundResource(R.drawable.bacckga1);
button = findViewById(R.id.button2);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(SettingsMain.this, MainActivity.class);
startActivity(intent);
}
});
song1 = findViewById(R.id.song1);
song2 = findViewById(R.id.song2);
song3 = findViewById(R.id.song3);
song4 = findViewById(R.id.song4);
album1 = findViewById(R.id.album1);
album2 = findViewById(R.id.album2);
album3 = findViewById(R.id.album3);
album4 = findViewById(R.id.album4);
album1.setImageResource(R.drawable.kanye);
album2.setImageResource(R.drawable.silksonic);
album3.setImageResource(R.drawable.davidguetta);
album4.setImageResource(R.drawable.mjthriller);
song1.setText("Play");
song2.setText("Play");
song3.setText("Play");
song4.setText("Play");
song1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(SettingsMain.this, MyService.class);
intent.putExtra("key",0);
startService(intent);
}
});
song2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(SettingsMain.this, MyService.class);
intent.putExtra("key",1);
startService(intent);
}
});
song3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(SettingsMain.this, MyService.class);
intent.putExtra("key",2);
startService(intent);
}
});
song4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(SettingsMain.this, MyService.class);
intent.putExtra("key",3);
startService(intent);
}
});
}
}
Thanks

Android reload WebView URL onNewToken from Firebase Messaging Center

I'm running a WebView Android App that points to a WebApp. Everything ok. But now, I'm having problem to refresh the url which is already loaded when the method onNewToken from FirebaseMessagingService is called and also inject a JS into it. I have heard about Intents and also found this question but can't really understand how and where to apply the Intents.
Here is what my code currently looks like:
MyFirebaseMessagingService:
package com.example.app;
import android.util.Log;
import com.google.firebase.messaging.FirebaseMessagingService;
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "MyFirebaseMessagingService";
#Override
public void onNewToken(String token) {
Log.d(TAG, "Refreshed token: " + token);
// I want to call the loadUrl here using a injected JS to send the token to the Web App
}
}
MyWebViewClient:
package com.example.app;
import android.content.Intent;
import android.net.Uri;
import android.util.Log;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;
class MyWebViewClient extends WebViewClient {
private static final String TAG = "MyWebViewClient";
#Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
String hostname;
// YOUR HOSTNAME
hostname = "192.168.0.11";
final Uri uri = request.getUrl();
Log.i(TAG, "Uri =" + uri);
if (uri.getHost() != null && uri.getHost().endsWith(hostname)) {
return false;
}
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
view.getContext().startActivity(intent);
return true;
}
}
MainActivity:
package com.example.app;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebSettings;
import android.webkit.WebView;
public class MainActivity extends Activity {
public WebView mWebView;
#Override
#SuppressLint("SetJavaScriptEnabled")
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mWebView = findViewById(R.id.activity_main_webview);
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setDomStorageEnabled(true);
webSettings.setDatabaseEnabled(true);
mWebView.setWebViewClient(new MyWebViewClient());
// REMOTE RESOURCE
mWebView.loadUrl("http://192.168.0.11:3000/");
// LOCAL RESOURCE
// mWebView.loadUrl("file:///android_asset/index.html");
}
#Override
public void onBackPressed() {
if(mWebView.canGoBack()) {
mWebView.goBack();
} else {
super.onBackPressed();
}
}
}
Yes you have to use Intents but at first use LocalBroadcastManager in your "MyFirebaseMessagingService" :
public static String REQUEST_ACCEPT="action.my.messaging";
#Override
public void onNewToken(String token) {
Log.d(TAG, "Refreshed token: " + token);
//after any refresh you will notice it to your activity (or fragment)
Intent intent = new Intent(REQUEST_ACCEPT);
intent.putExtra("key", "Any Extra Value Here");
LocalBroadcastManager.getInstance(getBaseContext()).sendBroadcast(intent);
}
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
//Or use it here after any message received
}
Then in your activity you can receive any notices and do the refresh or any action you want:
#Override
public void onCreate(Bundle savedInstanceState) {
// registering an observer (mMessageReceiver) to receive Intents
// with actions named as the value of REQUEST_ACCEPT.
LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver,
new IntentFilter(MyFirebaseMessagingService.REQUEST_ACCEPT));
}
// Our handler for received Intents. This will be called whenever an Intent
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// Get extra data included in the Intent
String value = intent.getStringExtra("key");
Log.d(TAG, "Got noticed: " + value );
}
};
#Override
protected void onDestroy() {
// Unregister since the activity is about to be closed.
LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
super.onDestroy();
}

How to prevent a service from terminating?

MainActivity.java
import android.content.Intent;
import android.os.Bundle;
import android.support.wearable.activity.WearableActivity;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends WearableActivity {
private TextView mTextView;
private static MainActivity instance;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextView = (TextView) findViewById(R.id.text);
// Enables Always-on
setAmbientEnabled();
final TextView text = findViewById(R.id.text);
text.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (text.getText().toString().equals("Started")) {
text.setText("Stoped");
stopService(new Intent(MainActivity.this,service.class));
} else {
text.setText("Started");
startService(new Intent(MainActivity.this,service.class));
}
}
});
}
public static MainActivity getInstance() {
return instance;
}
public void showToast(String toastMsg){
Toast.makeText(MainActivity.this, toastMsg, Toast.LENGTH_SHORT).show();
}
}
Service.java
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
import androidx.annotation.MainThread;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
public class service extends Service {
private boolean started = false;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i("serviceTest", "Service started by user.");
start();
return START_STICKY;
}
#Override
public void onDestroy() {
//Toast.makeText(this, "Service destroyed by user.", Toast.LENGTH_LONG).show();
Log.i("serviceTest", "Service destroyed by user.");
stop();
super.onDestroy();
}
private Timer timer;
private TimerTask timerTask = new TimerTask() {
#Override
public void run() {
if(started) {
start();
}
Log.i("serviceTest", "ServiceCalled!");
}
};
public void start() {
if(timer != null) {
return;
}
timer = new Timer();
timer.scheduleAtFixedRate(timerTask, 0, 10000);
}
public void stop() {
timer.cancel();
timer = null;
}
}
The code runs okay for about 13 or 14 times (i.e. the timer keeps on running for about 13 or 14 times) but suddenly the service stops and onDestroy is called.
Also, during debugging, I have noticed one strange condition: If I delete/comment the onDestroy() method form the code then the service runs always. It never closes on its own. (it only closes upon user input, which is fine)
Please suggest a solution so that the services do not get killed/ destroyed. Or if the OS/ System kills it, then the service starts again on its own.
Thnx
You will have to turn that background service into a foreground service, because of the limitations called Background Execution Limits that started from android Oreo.
Please check out this link for more better understanding: https://developer.android.com/about/versions/oreo/background

Android Bluetooth Discovery not working

I am trying to list bluetooth devices available periodically. The idea is to run the startDiscovery() fuction every 4 secs and list the visible devices.
package com.neondude.cupid;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;
public class MainActivity extends Activity {
Timer mTimer;
private ListView listView;
private ArrayList<String> mDeviceList = new ArrayList<String>();
private BluetoothAdapter mBluetoothAdapter;
private ArrayAdapter<String> BTArrayAdapter;
Handler mHandler = new Handler();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listView);
BTArrayAdapter = new ArrayAdapter<String>(this,R.layout.list_view);
listView.setAdapter(BTArrayAdapter);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter);
}
private void startTimer(){
mTimer = new Timer();
mTimer.scheduleAtFixedRate(new Mytask(), 4000, 1000 * 5);
}
class Mytask extends TimerTask {
#Override
public void run(){
mHandler.post(new Runnable(){
#Override
public void run(){
find();
}
});
}
}
public void find(){
if (mBluetoothAdapter.isDiscovering()) {
mBluetoothAdapter.cancelDiscovery();
}
else {
BTArrayAdapter.clear();
mBluetoothAdapter.startDiscovery();
registerReceiver(mReceiver, new IntentFilter(BluetoothDevice.ACTION_FOUND));
}
mBluetoothAdapter.startDiscovery();
}
final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action))
{
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
short rssi = intent.getShortExtra(BluetoothDevice.EXTRA_RSSI,Short.MIN_VALUE);
BTArrayAdapter.add(device.getName() + "\n" + device.getAddress() + "\n" + rssi);
BTArrayAdapter.notifyDataSetChanged();
}
}
};
#Override
protected void onDestroy() {
unregisterReceiver(mReceiver);
super.onDestroy();
}
}
I have included the startDiscovery() function in the timertask handler. But when i do this , the devices and not listed in my listView.
You should check if the bluetooth is on, and ask the user to turn on if is off:
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
else{
startTimer();
}
You could start the timer onActivityResult()
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// Check which request we're responding to
if (resultCode == RESULT_OK) {
// The user turn on the bluetooth
startTimer();
}
}
}
The startTimer() function is never called, therefore the timerTask does not begin.

how to set alarm when screen is off for android device?

Hi I want to set alarm notification when the mobile screen is off. My code is'
package com.my.timeout;
import java.util.Calendar;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.widget.Toast;
public class ScreenON_OFF_ACTIVITY extends Activity
{
AlarmManager am;
private static final int REQUEST_CODE = 0;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
onCreate1();
}
public void onCreate1() {
// initialize receiver
System.out.println("onCreate1 ");
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
BroadcastReceiver mReceiver = new ScreenReceiver();
registerReceiver(mReceiver, filter);
System.out.println("onCreate ");
}
#Override
protected void onPause() {
// when the screen is about to turn off
if (ScreenReceiver.screenOff) {
// this is the case when onPause() is called by the system due to a screen state change
System.out.println("SCREEN TURNED OFF");
} else {
// this is when onPause() is called when the screen state has not changed
System.out.println("this is when onPause() is called when the screen state has not changed ");
display_alarm();
}
super.onPause();
}
#Override
protected void onResume() {
// only when screen turns on
if (!ScreenReceiver.screenOff) {
// this is when onResume() is called due to a screen state change
System.out.println("SCREEN TURNED ON");
} else {
// this is when onResume() is called when the screen state has not changed
System.out.println(" this is when onResume() is called when the screen state has not changed ");
}
super.onResume();
}
}
ScreenReceiver.java
package com.my.timeout;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class ScreenReceiver extends BroadcastReceiver
{
public static boolean screenOff;
#Override
public void onReceive(Context context, Intent intent) {
System.out.println("onReceive ");
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
screenOff = true;
System.out.println("SCREEN TURNED OFF on BroadcastReceiver");
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
screenOff = false;
System.out.println("SCREEN TURNED ON on BroadcastReceiver");
}
Intent i = new Intent(context, UpdateService.class);
i.putExtra("screen_state", screenOff);
context.startService(i);
}
}
UpdateService.java
package com.my.timeout;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
public class UpdateService extends Service {
public void onCreate() {
super.onCreate();
// register receiver that handles screen on and screen off logic
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
BroadcastReceiver mReceiver = new ScreenReceiver();
registerReceiver(mReceiver, filter);
}
#Override
public void onStart(Intent intent, int startId) {
boolean screenOn = intent.getBooleanExtra("screen_state", false);
if (!screenOn) {
System.out.println("Screen is off");
} else {
System.out.println("Screen is on");
}
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
Now i want to set alarm when the screen has been go off. How can i do this.Can anybody tell me? thanks in advance.

Categories

Resources