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);
Related
I have created a new layout name dialog_exit for onBackPressed but when I install and open, my application can not open and showing error close app
Please review my whole code and guide me how can I solve this problem
Here is my main activity code
public class MainActivity extends AppCompatActivity {
public Dialog mDialog;
public Button mDialogyes, mDialogno;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
createDialog();
}
private void createDialog() {
mDialog = new Dialog(this);
mDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
mDialog.setContentView(R.layout.dialog_exit);
mDialog.setCanceledOnTouchOutside(true);
mDialog.setCancelable(true);
mDialogyes = (Button) findViewById(R.id.yes);
mDialogno = (Button) findViewById(R.id.no);
mDialogyes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.setFlags(intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.addCategory(Intent.CATEGORY_HOME);
startActivity(intent);
finish();
System.exit(0);
mDialogno.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mDialog.dismiss();
}
});
}
});
}
#Override
public void onBackPressed() {
mDialog.show();
}
}
Here is my layout code as screenshot because
stackoverflow not allow me to add more code that why sharing image
Updated code of createDialog function
private void createDialog() {
mDialog = new Dialog(this);
mDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
mDialog.setContentView(R.layout.dialog_exit);
mDialog.setCanceledOnTouchOutside(true);
mDialog.setCancelable(true);
mDialogyes = (Button) mDialog.findViewById(R.id.yes);
mDialogno = (Button) mDialog.findViewById(R.id.no);
mDialogyes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.setFlags(intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.addCategory(Intent.CATEGORY_HOME);
startActivity(intent);
finish();
System.exit(0);
}
});
mDialogno.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mDialog.dismiss();
}
});
}
try this code
mDialogyes = (Button)mDialogyes. findViewById(R.id.yes);
mDialogno = (Button)mDialogyes. findViewById(R.id.no);
mDialogyes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.setFlags(intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.addCategory(Intent.CATEGORY_HOME);
startActivity(intent);
finish();
System.exit(0);
}
});
mDialogno.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mDialog.dismiss();
}
});
You have to do like this
mDialogyes = (Button) mDialog.findViewById(R.id.yes);
mDialogno = (Button) mDialog.findViewById(R.id.no);
I have tried everything and whatever I could to solve this problem. At last I am posting it here to get a solution (New to Android).
I have made an android scanner app and I am using ZXing open source code. The problem is after scan I am trying to send the scan result to another activity but unable to do.
Here is my code:
public class MainActivity extends AppCompatActivity
implements ZXingScannerView.ResultHandler, NavigationView.OnNavigationItemSelectedListener {
private ZXingScannerView mScannerView;
private int CALL_SCANNER_APP;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Scan Button code
public void onClick(View v) {
ZXingScannerView mScannerView = new ZXingScannerView(this);
setContentView(mScannerView);
mScannerView.setResultHandler(this);
mScannerView.startCamera();
//startActivityForResult(mScannerView1, CALL_SCANNER_APP);
}
#Override
protected void onPause (){
super.onPause();
mScannerView.stopCamera();
}
#Override
public void handleResult(Result result) {
ResultActivity.tvresult.setText(result.getText());
/*Log.w("handleReuslt", result.getText());
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Scan Result");
builder.setMessage(result.getText());
AlertDialog alertDialog = builder.create();
//alertDialog.show();
builder.setPositiveButton("Result", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(MainActivity.this, MainActivity.class);
startActivity(intent);
}
});
builder.setNegativeButton("OK", null).show();*/
//Resume Scanning
//mScannerView.resumeCameraPreview(this);
}
There is one method which send results from One activity to other activity is scanActivityForResult() but in my case I am not using intent on public void onClick(View v)
So how do I achieve this.
Thanks!
Use Below code into the button click.
Intent intent = new Intent(SelectOptionActivity.this, CaptureActivity.class);
intent.putExtra("SCAN_MODE", "ONE_D_MODE");
intent.putExtra("SCAN_FORMATS", "CODE_39,CODE_93,CODE_128,DATA_MATRIX,ITF,CODABAR,EAN_13,EAN_8,UPC_A,QR_CODE");
intent.setAction(Intents.Scan.ACTION);
startActivityForResult(intent, 1);
And override this method to get result of scanning.
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == 1 && resultCode == RESULT_OK) {
final String contents = intent.getStringExtra(Intents.Scan.RESULT);
final String formatName = intent.getStringExtra(Intents.Scan.RESULT_FORMAT);
}
}
in handleDecodeInternally you directly intent the Capture Activity to desired Activity
private void handleDecodeInternally(Result rawResult, ResultHandler resultHandler, Bitmap barcode) {
maybeSetClipboard(resultHandler);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
if (resultHandler.getDefaultButtonID() != null && prefs.getBoolean(PreferencesActivity.KEY_AUTO_OPEN_WEB, false)) {
resultHandler.handleButtonPress(resultHandler.getDefaultButtonID());
return;
}
statusView.setVisibility(View.GONE);
viewfinderView.setVisibility(View.GONE);
resultView.setVisibility(View.GONE);
Intent intent = new Intent(CaptureActivity.this, AfterCaptureActivity.class);
startActivity(intent);
finish();
I'm going through the Facebook Android SDK (https://developers.facebook.com/docs/facebook-login/android) and am finding it difficult to understand. I simply want to open a new activity after (successful) login, though the steps show alot of other code and I'm not sure which ones I require. Here's my code:
activity_main.xml
<com.facebook.login.widget.LoginButton
android:id="#+id/fb_login_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
tools:layout_editor_absoluteY="496dp" />
MainActivity.java
public class MainActivity extends AppCompatActivity {
Button or_email;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
or_email = (Button)findViewById(R.id.or_email);
or_email.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(MainActivity.this, Register.class);
MainActivity.this.startActivity(i);
}
});
}
}
Register.java (for blank activity_register.xml)
public class Register extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
}
}
So basically, I just want to open activity_register.xml after successfully logging in. So i'd imagine I add a new Intent under the onSuccess() method. However I'm not sure where exactly I'm supposed to put this code, and also whether it needs the previous code block (the FragmentActivity) in order to work. So If someone could explain to me how each of those 3 code blocks are working in detail. that would be great.
ps: I've already registered my app id and all that so the button is working, I just want it to open a new activity after logging in. Right now it just goes back to activity_main after logging in.
Edit: Following code doesn't open up activity_register, it just goes back to activity_main
public class MainActivity extends AppCompatActivity {
Button or_email;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FacebookSdk.sdkInitialize(getApplicationContext());
CallbackManager mFacebookCallbackManager = CallbackManager.Factory.create();
setContentView(R.layout.activity_main);
LoginButton mFacebookSignInButton = (LoginButton)findViewById(R.id.fb_login_btn);
mFacebookSignInButton.registerCallback(mFacebookCallbackManager,
new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(final LoginResult loginResult) {
//TODO: Use the Profile class to get information about the current user.
Intent intent = new Intent(MainActivity.this, Register.class);
startActivity(intent);
}
#Override
public void onCancel() {
Toast.makeText(getApplicationContext(), "Cancel", Toast.LENGTH_SHORT).show();
}
#Override
public void onError(FacebookException error) {
Toast.makeText(getApplicationContext(), "Error", Toast.LENGTH_SHORT).show();
}
}
);
or_email = (Button)findViewById(R.id.or_email);
or_email.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(MainActivity.this, Register.class);
MainActivity.this.startActivity(i);
}
});
}
}
Try this:
in your activity: Make sure you do
Initilize facebook sdk and accessTokenTracker in onCreate()
Give permission in your login Button and register the callback.
In onSuccess() method start new Activity
Finally override the onActivityResult() method and add the callbackManger.onActivityResult() with the request code.
public class MainActivity extends AppCompatActivity {
Button or_email;
CallbackManager mFacebookCallbackManager;
private AccessTokenTracker accessTokenTracker;
private ProfileTracker mProfileTracker;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
setContentView(R.layout.activity_main);
mFacebookCallbackManager = CallbackManager.Factory.create();
accessTokenTracker = new AccessTokenTracker() {
#Override
protected void onCurrentAccessTokenChanged(AccessToken oldToken, AccessToken newToken) {
}
};
accessTokenTracker.startTracking();
LoginButton mFacebookSignInButton = (LoginButton)findViewById(R.id.fb_login_btn);
mFacebookSignInButton.setReadPermissions(Arrays.asList(
"public_profile", "email", "user_birthday", "user_friends"));
mFacebookSignInButton.registerCallback(mFacebookCallbackManager, callback);
or_email = (Button)findViewById(R.id.or_email);
or_email.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(MainActivity.this, Register.class);
MainActivity.this.startActivity(i);
}
});
}
private FacebookCallback<LoginResult> callback = new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
try {
if (Profile.getCurrentProfile() == null) {
mProfileTracker = new ProfileTracker() {
#Override
protected void onCurrentProfileChanged(Profile profile_old, Profile profile_new) {
profile = profile_new;
Log.v("facebook - profile", profile_new.getFirstName());
mProfileTracker.stopTracking();
}
};
mProfileTracker.startTracking();
} else {
profile = Profile.getCurrentProfile();
Log.v("facebook - profile", profile.getFirstName());
}
Intent intent = new Intent(getApplicationContext(), Register.class);
startActivity(intent);
finish();
} catch (Exception e) {
Log.d("ERROR", e.toString());
}
}
#Override
public void onCancel() {
Toast.makeText(getApplicationContext(), "Cancelled", Toast.LENGTH_LONG).show();
}
#Override
public void onError(FacebookException e) {
Log.d("FACEBOOK ERRROR", e.toString());
Toast.makeText(getApplicationContext(), "Something went wrong!! Please try again", Toast.LENGTH_LONG).show();
}
};
#Override
protected void onActivityResult(int requestCode, int responseCode, Intent intent) {
super.onActivityResult(requestCode, responseCode, intent);
mFacebookCallbackManager.onActivityResult(requestCode, responseCode, intent);
}
}
in manifest:
<activity
android:name="com.facebook.FacebookActivity"
android:configChanges="keyboard|keyboardHidden|screenLayout|screenSize|orientation"
android:label="#string/app_name"
android:theme="#android:style/Theme.Translucent.NoTitleBar" />
Make sure your add the app_id in manifest...
Add this code inside onCreate() method
FacebookSdk.sdkInitialize(getApplicationContext());
CallbackManager mFacebookCallbackManager = CallbackManager.Factory.create();
setContentView(R.layout.activity_main);
LoginButton mFacebookSignInButton = (LoginButton)findViewById(R.id.fb_login_btn);
mFacebookSignInButton.registerCallback(mFacebookCallbackManager,
new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(final LoginResult loginResult) {
//TODO: Use the Profile class to get information about the current user.
Intent intent = new Intent(MainActivity.this, Register.class);
startActivity(intent);
}
#Override
public void onCancel() {
Toast.makeText(getApplicationContext(), "Cancel", Toast.LENGTH_SHORT).show();
}
#Override
public void onError(FacebookException error) {
Toast.makeText(getApplicationContext(), "Error", Toast.LENGTH_SHORT).show();
}
}
);
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));
}
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);
}