how to extract the string value in Android services from an activity? - java

how to extract the string value in Android services from an activity?
My activity has a edit text, the entered string must be received in my services.
TempLaunch.java :
public class TempLaunch extends Activity {
private EditText text;
private Button okbtn;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.templaunch);
addListenerOnButton();
}
public void addListenerOnButton() {
text = (EditText) findViewById(R.id.edittext_newid);
okbtn = (Button) findViewById(R.id.button_newid);
okbtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(TempLaunch.this, "In Temp launch class ",Toast.LENGTH_SHORT).show();
Toast.makeText(TempLaunch.this, text.getText(),Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
Toast.makeText(TempLaunch.this, "I am in Main activity class ",Toast.LENGTH_SHORT).show();
startActivity(intent);
}
});
Intent i = new Intent(this, MusicService.class);
i.putExtra("DD_URL", text.getText().toString());
//startActivity(i);
}
}
MusicService.java
public class MusicService extends Service {
#Override
public void onCreate() {
super.onCreate();
String url = null;
Intent intent = getIntent();
String id = intent.getStringExtra("DD_URL");
System.out.println("Rosh :" + id);
Toast.makeText(MusicService.this, "I am in Service:"+ id,Toast.LENGTH_SHORT).show();
...
Please help me out with this regard.
Thanks in advance

You may use sendBroadcast(intent); which will broadcast the EditText from your Activity A.
Then you need to call onReceive(Context context, Intent intent) within your Service class. This method is called when the BroadcastReceiver is receiving an Intent broadcast, in your case will be sent from Activity A.
private final BroadcastReceiver receiver = new BroadcastReceiver()
{
#Override
public void onReceive(Context context, Intent intent)
{
// Do something
}
};
//Register your receiver in onResume:
#Override
protected void onResume()
{
super.onResume();
IntentFilter filter = new IntentFilter();
filter.addAction("SOME_ACTION");
registerReceiver(receiver, filter);
}
//Unregister the receiver in onPause:
#Override
protected void onPause()
{
super.onPause();
unregisterReceiver(receiver);
}

Related

How to update the UI with BroadcastReceiver onReceive in Android?

I want to update the UI according to the WiFi status in my Android app in Java. I am unable to update the UI to show the new string. Please help me.
Here is my code
public class MainActivity extends AppCompatActivity {
IntentFilter intentFilter = new IntentFilter();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(new NetworkConnectionReceiver(), intentFilter);
TextView displayStatus = findViewById(R.id.displayStateTextView);
}
}
class NetworkConnectionReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
Log.i("MyReceiver", Boolean.toString(wifiManager.isWifiEnabled()));
}
}
Use this code:
public class MainActivity extends AppCompatActivity {
...
BroadcastReceiver br = new BroadcastReceiver(){
#Override
public void onReceive( Context context, Intent intent ){
//update UI here directly
View view = findViewById( R.id.example );
}
};
#Override
protected void onResume(){
super.onResume();
// Check state here
...
IntentFilter filter = new IntentFilter();
filter.addAction( ConnectivityManager.CONNECTIVITY_ACTION );
registerReceiver( br, filter);
}
#Override
protected void onPause(){
super.onPause();
unregisterReceiver( br );
}
...
}
You can do it using interface
interface WifiStateListener{
void onStateChanged(Boolean enabled);
}
Then add a constructor to pass the WifiStateListener to BroadcastReceiver
class NetworkConnectionReceiver extends BroadcastReceiver {
private WifiStateListener mWifiStateListener;
public NetworkConnectionReceiver(WifiStateListener wifistateListener){
mWifiStateListener = wifistateListener;
}
#Override
public void onReceive(Context context, Intent intent) {
WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
if(mWifiStateListener != null){
mWifiStateListener.onStateChanged(wifiManager.isWifiEnabled());
}
Log.i("MyReceiver", Boolean.toString(wifiManager.isWifiEnabled()));
}
}
And in Activity, while registering receiver you can pass the interface
registerReceiver(new NetworkConnectionReceiver(enabled -> {
//do based on wifi state change
}), intentFilter);
Other options are to use EventBus, Observables etc
You can user LocalBroadCastManager.
First write broadCastReceiver in activity
register that broadcast with LocalBroadCastManager in onResume
unregister that broadcast with LocalBroadCastManager in onPause as well
than write Broadcast of internet connection and call LocalBroadCastManager which you register in activity
private BroadcastReceiver broadCastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction() == "local_broadcast_update_UI"){
updateUI()
}
}
};
#Override
protected void onResume(){
super.onResume();
LocalBroadcastManager.getInstance(this).registerReceiver( broadCastReceiver, new
IntentFilter("local_broadcast_update_UI"));
}
#Override
protected void onPause(){
super.onPause();
LocalBroadcastManager.getInstance(this).unregisterReceiver("local_broadcast_update_UI");
}
public class NetworkChangeReceiver extends BroadcastReceiver {
#Override
public void onReceive(final Context context, final Intent intent) {
final ConnectivityManager connMgr = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
final android.net.NetworkInfo wifi = connMgr
.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
final android.net.NetworkInfo mobile = connMgr
.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if (wifi.isAvailable() || mobile.isAvailable()) {
LocalBroadcastManager.getInstance(context).sendBroadcast(new
Intent("local_broadcast_update_UI"));
}
}
}

startActivity(intent) causes error on Android

I did onClick at xml level. It was okay for a few times, but this one time causes error. I can't seem to find where the error is from. But it said that startActivity(intent); is where the error is.
public void callNextSignUpScreen2(View view) {
Intent intent = new Intent(getApplicationContext(),SignUp3.class);
startActivity(intent);
}
This is my full code
public class SignUp2 extends AppCompatActivity {
//Variable
ImageView back_icon;
Button next, login;
TextView title_text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_up2);
//Hooks
back_icon = findViewById(R.id.signup_back_btn);
next = findViewById(R.id.signup_next_next_btn);
login = findViewById(R.id.login_btn);
title_text = findViewById(R.id.signup_title_text);
}
public void callNextSignUpScreen2(View view) {
Intent intent = new Intent(getApplicationContext(),SignUp3.class);
startActivity(intent);
}
public void callBackSign2(View view) {
Intent intent = new Intent(getApplicationContext(),SignUp.class);
startActivity(intent);
}
}

Toggle Background/Foreground Modes

I'm trying to make it so that when you press the power button to turn off the android, my app goes into background mode. When you press the power button to turn on the android, my app should go into foreground mode.
The error I get is:
java.lang.RuntimeException: Error receiving broadcast Intent {
act=android.intent.action.SCREEN_ON flg=0x50000010 }
The error comes from the intent with FLAG_ACTIVITY_CLEAR_TOP
Here's the MainActivity:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
BroadcastReceiver mReceiver = new ScreenReceiver(MainActivity.this, this);
registerReceiver(mReceiver, filter);
moveTaskToBack(true);
}
}
Here's the BroadcastReceiver:
public class ScreenReceiver extends BroadcastReceiver {
MainActivity mainAct;
Context ctx;
public ScreenReceiver(MainActivity act, Context con) {
mainAct = act;
ctx = con;
}
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
mainAct.moveTaskToBack(true);
System.out.println("OFF");
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
Intent i = new Intent(ctx, ScreenReceiver.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
mainAct.startActivity(i);
System.out.println("ON");
}
}
}
I'm using code from the following tutorial:
https://thinkandroid.wordpress.com/2010/01/24/handling-screen-off-and-screen-on-intents/
The mistake was passing ScreenReceiver.class instead of MainActivity.class into the intent. Here's the corrected version:
public class ScreenReceiver extends BroadcastReceiver {
MainActivity mainAct;
Context ctx;
public ScreenReceiver(MainActivity act, Context con) {
mainAct = act;
ctx = con;
}
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
mainAct.moveTaskToBack(true);
System.out.println("OFF");
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
Intent i = new Intent(ctx, MainActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
mainAct.startActivity(i);
System.out.println("ON");
}
}
}

How to Stop playing Service in android

I have a question about Service and BroadCast in android.I create an Alarm Clock page that using Alarm Reciver class(it's extend class of BroadCast) for go to RingtonePlaying Service class to start a music. Now I want to stop it when click on turn_off button but I can't do that. Please Help me
Thanks
AlarmClock class:
private Button turn_on;
public Button turn_off;
private TextView update_text;
Context context;
AlarmManager alarm_manager;
TimePicker time_picker;
PendingIntent pending_intent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_alarm_clock);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
onButtonClickAlarm();
}
private void onButtonClickAlarm() {
this.context=this;
turn_on=(Button)findViewById(R.id.alarm_on);
turn_off=(Button)findViewById(R.id.alarm_off);
update_text=(TextView)findViewById(R.id.update_text);
alarm_manager=(AlarmManager)getSystemService(ALARM_SERVICE);
time_picker=(TimePicker)findViewById(R.id.timePicker);
final Calendar calendar=Calendar.getInstance();
final Intent my_intent=new Intent(this,AlarmReciever.class);
turn_on.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
update_text.setText("Alarm Turn On");
calendar.set(Calendar.HOUR_OF_DAY,time_picker.getCurrentHour());
pending_intent= PendingIntent.getBroadcast(AlarmClock.this,0,my_intent,PendingIntent.FLAG_UPDATE_CURRENT);
alarm_manager.set(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis(),pending_intent);
}
});
final RingtonPlayingService rington=new RingtonPlayingService();
turn_off.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
update_text.setText("Alarm Turn Off");
}
});
}}
AlarmReciver Class:
public class AlarmReciever extends BroadcastReceiver {
AlarmClock alarmClock=new AlarmClock();
#Override
public void onReceive(Context context, Intent intent) {
Log.e("AlarmReciever","Alarm Reciever Error");
Intent intent_service=new Intent(context,RingtonPlayingService.class);
context.startService(intent_service);
}}
RingtonPlayingService:
public class RingtonPlayingService extends Service {
public static MediaPlayer mediaPlayer;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent,int flags , int startId) {
if(mediaPlayer==null)
{
mediaPlayer = MediaPlayer.create(this, R.raw.relax);
mediaPlayer.start();
}
return START_NOT_STICKY;
}
#Override
public boolean onUnbind(Intent intent) {
mediaPlayer.stop();
return super.onUnbind(intent);
}
#Override
public void onDestroy() {
Toast.makeText(this, "onDestroy is Called", Toast.LENGTH_SHORT).show();
mediaPlayer.stop();
}}
try this to stop your service
Intent inten = new Intent(getApplicationContext(), YourService.class);
stopService(inten);
If you want to cancel the alarm before starting the service then use following code:
Intent alarmIntent = new Intent(this, AlarmReceiver.class);
pendingIntent = PendingIntent.getBroadcast(this, 0, alarmIntent, 0);
manager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
manager.cancel(pendingIntent);
if you want to stop service then use following code:
Intent intent_service=new Intent(context,RingtonPlayingService.class);
stopService(intent_service);

Without Button click How to call MyService class in MainActivity in android studio

Without Button click How to call MyService class in MainActivity. My issue is to call MyService class in MainActivity class because when app start notification automatically started.
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MyService my = new MyService();
}
}
MyService.Java
public class MyService extends Service {
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
showNotification();
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
}
private void showNotification() {
NotificationCompat.Builder mBuilder =
(NotificationCompat.Builder) new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_loc)
.setContentTitle("Welcome to Brillio")
.setContentText("Hello Mansur, Welcome to Brillio! You'll be shortly attended by Renji! ")
.setPriority(2)
.setOnlyAlertOnce(false);
Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
mBuilder.setSound(alarmSound);
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(2001, mBuilder.build());
}
}
Without any user interaction you can start service like when your activity is open you can start service intent
#Override
public void onResume() {
super.onResume();
startService(new Intent(this, MyService.class));
}
Add this to onCreate() method:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startService(new Intent(this, MyService.class));
}

Categories

Resources