I was learning broadcast receiver concept, so I tried making demo apps for sending broadcast and receiving custom private broadcast
This is my Broadcast Sender App code :
public class MainActivity extends AppCompatActivity {
TextView senderTextView;
Button sendButton;
private int counter;
//This is our anonymous class which will receive broadcast when sent from send button and set our text view
private final BroadcastReceiver innerReceiverAnonymousClass = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
//if our (com.example.PRIVATE_BROADCAST) broadcast equals to the intent received here from intent filter
if("com.example.PRIVATE_BROADCAST".equals(intent.getAction())){
//counter variable for tracking no. of times broadcast is sent
counter++;
//then this means broadcast has been sent in mobile
//set text
senderTextView.setText("Broadcast Sent " + counter + " times");
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//initializing views
senderTextView = findViewById(R.id.senderTextView);
sendButton = findViewById(R.id.sendButton);
//Setting onClick Listener on sendButton
sendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Calling Broadcast Method
Broadcast();
}
});
}
//Broadcast Method
private void Broadcast(){
//Creating private broadcast event
Intent intent = new Intent("com.example.PRIVATE_BROADCAST");
//Adding String to our intent
intent.putExtra("BROADCAST_EXTRA_DATA","This is Private Broadcast");
//Sending our private broadcast to our android mobile
sendBroadcast(intent);
}
#Override
protected void onStart() {
super.onStart();
//Intent filter will filter out intent from all the broadcasts happening in mobile
// on basis of action and pass it to innerReceiverAnonymousClass
IntentFilter intentFilter = new IntentFilter("com.example.PRIVATE_BROADCAST");
registerReceiver(innerReceiverAnonymousClass,intentFilter);
}
#Override
protected void onStop() {
super.onStop();
unregisterReceiver(innerReceiverAnonymousClass);
}
This is my Broadcast Receiver app :
public class MainActivity extends AppCompatActivity {
TextView receiverTextView;
//Our anonymous private broadcast receiver class
//We can also make a separate class java class that will extend BroadcastReceiver class
//But we are using an anonymous so that we can get control of text view i.e. UI
private final BroadcastReceiver privateBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if("com.example.PRIVATE_BROADCAST".equals(intent.getAction())){
Log.d("APP_LOGS", "Broadcast Received");
Toast.makeText(context, "Private Broadcast Received", Toast.LENGTH_SHORT).show();
String broadcastString = intent.getStringExtra("BROADCAST_EXTRA_DATA");
receiverTextView.setText("Broadcast Received : " + broadcastString);
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
receiverTextView = findViewById(R.id.receiverTextView);
}
#Override
protected void onStart() {
super.onStart();
IntentFilter intentFilter = new IntentFilter("com.example.PRIVATE_BROADCAST");
registerReceiver(privateBroadcastReceiver,intentFilter);
}
#Override
protected void onStop() {
super.onStop();
unregisterReceiver(privateBroadcastReceiver);
}
When I press send Broadcast button textview inside sender activity sets to "Broadcast sent 1 times which means our intent is getting broadcasted but toast from my receiver app doesn't show which means I am not able to get broadcast there.
Can someone help me with this.
Thanks in advance.
Related
I want to play my ringtone in my android app in background(for version O and above) even if application is closed and stop playing if i stop from my app.
I used service in my application but the music is stopped when i closed my app.
How can i achieve this ??
Here is my Service class:
public class MyService extends Service {
MediaPlayer player;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
player=MediaPlayer.create(this, Settings.System.DEFAULT_RINGTONE_URI);
player.setLooping(true);
player.setVolume(100,100);
player.start();
player.start();
return START_STICKY;
}
#Override
public void onDestroy() {
player.stop();
player.release();
super.onDestroy();
}
}
and here is my MainActivity class from where I'm starting and stopping the service:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void Start(View view) {
startService(new Intent(this,MyService.class));
}
public void Stop(View v){
stopService(new Intent(this,MyService.class));
}
public void go(View view) {
startActivity(new Intent(MainActivity.this,NotActivity.class ));
}
}
From the code that you submitted, you have never invoked the service of the player. call the functions that you have created in oncreate method that should do the trick.
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
//button objects
private Button buttonStart;
private Button buttonStop;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//getting buttons from xml
buttonStart = (Button) findViewById(R.id.buttonStart);
buttonStop = (Button) findViewById(R.id.buttonStop);
//attaching onclicklistener to buttons
buttonStart.setOnClickListener(this);
buttonStop.setOnClickListener(this);
}
#Override
public void onClick(View view) {
if (view == buttonStart) {
//starting service
startService(new Intent(this, MyService.class));
} else if (view == buttonStop) {
//stopping service
stopService(new Intent(this, MyService.class));
}
}
}
note: Create two buttons to start and stop the service
For more info check out: https://www.simplifiedcoding.net/android-service-example/
I have a string that I'm trying to pass to my main activity that is bound to this service. The data doesn't seem to be making it through to the other side and I've tried a plethora of techniques. Any help would be appreciated
Here's the service
public int onStartCommand(Intent intent, int flags, int startId) {
String thename=intent.getStringExtra("stockName");
String TAG="hello";
Intent putIntent=new Intent(LocalService.this,Binding.class);
if(thename.equals("AMZN"))
{
//Toast.makeText(this, "The price is $1,755.25", Toast.LENGTH_LONG).show();
putIntent.putExtra("theName","WORKED");
}
and here is the activity itself
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_binding);
final Button priceButton=findViewById(R.id.priceButton);
final EditText stockPrice=findViewById(R.id.stockText);
final Intent theIntent=new Intent(Binding.this,LocalService.class);
priceButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String stockText=stockPrice.getText().toString();
theIntent.putExtra("stockName",stockText);
startService(theIntent);
Intent getit=getIntent();
String name=getit.getParcelableExtra("theName");
Toast.makeText(getApplicationContext(), name, Toast.LENGTH_LONG).show();
}
});
}
I tried adding a BroadcastReceiver to your code (it's not that pretty), I commented the lines I added. It's possible that I've missed something or made an error. Feel free to ask if your get any errors or read https://developer.android.com/reference/android/content/BroadcastReceiver
Good luck!
Your service
public int onStartCommand(Intent intent, int flags, int startId) {
//String for the BroadcastReceiver to listen for.
public static final String BROADCAST_STRING = "your.package.or.whatever.you.want.sending";
String thename=intent.getStringExtra("stockName");
String TAG="hello";
Intent putIntent=new Intent(BROADCAST_STRING);
if(thename.equals("AMZN"))
{
//Toast.makeText(this, "The price is $1,755.25", Toast.LENGTH_LONG).show();
putIntent.putExtra("theName","WORKED");
}
//Broadcast sent and picked up in Activity.
sendBroadcast(putIntent);
Your Activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_binding);
final Button priceButton=findViewById(R.id.priceButton);
final EditText stockPrice=findViewById(R.id.stockText);
private BroadcastReceiver broadcastReceiver;
final Intent theIntent=new Intent(Binding.this,LocalService.class);
//Adds a filter to the broadcastReceiver, what it should listen for
IntentFilter filter = new IntentFilter();
filter.addAction("your.package.or.whatever.you.want.sending");
//Triggered when a broadcast is picked up
broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
//Get intent and do what you want
};
// Register the broadcastReceiver and filter
this.registerReceiver(broadcastReceiver, filter);
priceButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String stockText=stockPrice.getText().toString();
theIntent.putExtra("stockName",stockText);
startService(theIntent);
Intent getit=getIntent();
String name=getit.getParcelableExtra("theName");
Toast.makeText(getApplicationContext(), name, Toast.LENGTH_LONG).show();
}
});
}
I want to implement Google Tag Manager to track the user interacts with my app, I have followed the guide from Google Docs but I faced some issues.
This is my Main Activity
public class MainActivity extends AppCompatActivity {
private static final String CONTAINER_ID = "GTM-TRFZVD5";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TagManager tagManager = TagManager.getInstance(this);
tagManager.setVerboseLoggingEnabled(true);
PendingResult<ContainerHolder> pendingResult =
tagManager.loadContainerPreferNonDefault(CONTAINER_ID, R.raw.gtm_trfzvd5);
pendingResult.setResultCallback(new ResultCallback<ContainerHolder>() {
#Override
public void onResult(#NonNull ContainerHolder containerHolder) {
ContainerHolderSingleton.setContainerHolder(containerHolder);
Container container = containerHolder.getContainer();
if(!containerHolder.getStatus().isSuccess()){
Log.e(MainActivity.class.getSimpleName(), "Failure loading container");
return;
}
ContainerLoadedCallback.registerCallbackForContainer(container);
containerHolder.setContainerAvailableListener(new ContainerLoadedCallback());
startAnotherActivity();
}
}, 2, java.util.concurrent.TimeUnit.SECONDS);
}
private void startAnotherActivity(){
Intent intent = new Intent(MainActivity.this, AnotherActivity.class);
startActivity(intent);
}
This is the Activity that user will interact
public class AnotherActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_another);
Button btn = (Button) findViewById(R.id.btn);
GTMUtils.pushOpenScreenEvent(getApplicationContext(), AnotherActivity.class.getSimpleName());
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
GTMUtils.pushClickButtonEvent(getApplicationContext(),
"btn");
}
});
}
And these are two methods to push the event to Google Analytics
public static void pushOpenScreenEvent(Context context, String screenName){
DataLayer dataLayer = TagManager.getInstance(context).getDataLayer();
dataLayer.push(DataLayer.mapOf("event", "openScreen", "screenName", screenName));
}
public static void pushClickButtonEvent(Context context, String btnEventName){
DataLayer dataLayer = TagManager.getInstance(context).getDataLayer();
dataLayer.push(DataLayer.mapOf("event", "videoPlay", "videoName", btnEventName));
}
I copied exactly from Google Guide but I when I ran the app, it only pushed the first event ("open screen") and the click button didn't send anything.
So did I do something wrong?
A Activity execute below code.
Call Test Activity passing arraylist "bus_list".
But Test Activity new_bus_list_array = I.getParcelableArrayListExtra("bus_list") returns null.
new_bus_list_array Class "Parcelable" has been implemented.
I don't know why.
please help.
Intent intent;
intent = new Intent(_context, Test.class);
intent.putParcelableArrayListExtra("bus_list", (ArrayList<? extends Parcelable>) new_bus_list_array);
intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(intent);
[Test.java]
public class Test extends AppCompatActivity {
List<Bus_List> new_bus_list_array = new ArrayList<Bus_List>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
Intent I = getIntent();
new_bus_list_array = I.getParcelableArrayListExtra("bus_list");
}
}
You can also do this way (using BrodCastManager)
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Your intent action
Intent intent = new Intent(value.equals("AccountFragment") ? "sendMeData" : "analysisMe");
tempList.clear();
intent.putExtra("analysisData", (Parcelable) balanceMap.get(keylist.get(position)));
tempList.addAll(myRecord); // for backup because we are removing other data so it affect on parent
// send like this
intent.putParcelableArrayListExtra("RecordData", (ArrayList<? extends Parcelable>) tempList);
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
In your Another Activity where you Received Data
(After register to BroadcastManger)
BroadcastReceiver analysisRecevier = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
AccountAnalysisModel currentAccountBalModel = intent.getParcelableExtra("analysisData");
recordData = intent.getParcelableArrayListExtra("RecordData");
}
};
I have a Main Activity from where I call an Splash Screen Intent which destroys itself after 3 seconds but between the lifecycle of the Splash Screen Intent the Main Activity destroys itself too (which is wrong!).. so when the Splash Screen Intent is finished the App crashes because the Main Activity has been destroyed itself.
I really Appreciate if someone can help me with this, I'm really out of ideas at this point.
Here's my code:
MainActivity.java
public class MainActivity extends Activity {
private WebView webview;
public MainActivity() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
log.debug("onCreate(): " + savedInstanceState);
MyApplication.startSomeMobileCore(this);
MyApplication.startSomeMobileNotifier(this);
setContentView(R.layout.main);
this.onNewIntent(this.getIntent());
}
#Override
protected void onStart() {
log.debug("onStart()");
super.onStart();
}
#Override
protected void onRestart() {
super.onRestart();
this.wasRestarted = true;
}
#Override
protected void onResume() {
super.onResume();
}
protected void onPause() {
super.onPause();
this.receivedIntent = false;
}
protected void onStop() {
super.onStop();
this.receivedIntent = false;
}
public void onDestroy() {
super.onDestroy();
}
#Override
public void onNewIntent(Intent intent) {
log.debug("onNewIntent(): " + intent);
super.onNewIntent(intent);
if(intent == null) {
log.warn("Received null intent, will ignore");
}
if ("OK".equals(authCode)) {
if (intent != null && intent.getData() != null &&
("content".equals(intent.getData().getScheme()) ||
"http".equals(intent.getData().getScheme()))) {
log.debug("intent.getData() :" + intent.getData() + "; intent.getData().getScheme() : " + intent.getData().getScheme());
String requestedPath;
if ("http".equals(intent.getData().getScheme())) {
requestedPath = URLDecoder.decode(intent.getData().toString());
} else {
requestedPath = intent.getData().getPath();
}
showResource(requestedPath);
} else {
log.debug("Intent without data -> go to entry page after splash screen");
showResource(Configuration.properties.getProperty("PORTAL"));
}
} else {
Intent errorIntent = new Intent(this, ErrorIntent.class);
startActivity(errorIntent);
// finish actual activity
finish();
}
log.debug("Show splash screen");
Intent intentSplash = new Intent(this, SplashIntent.class);
startActivity(intentSplash);
}
void showResource(String resourceToShow) {
webview = (WebView)findViewById(R.id.browser);
webview.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
webview.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
webview.setWebViewClient(new WebViewClient());
webview.getSettings().setJavaScriptEnabled(true);
webview.getSettings().setDomStorageEnabled(true);
webview.loadUrl(resourceToShow);
}
}
}
here is my SplashIntent.java
public class SplashIntent extends Activity {
// Time splash screen should be shown (in ms)
private static final int splashTime = 3000;
static Logger log = Logger.getLogger(SplashIntent.class);
#Override
public void onCreate(final Bundle savedInstanceState) {
log.debug("SplashIntent: onCreate");
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
log.debug("SplashIntent: killing splash");
finish();
}
}, splashTime);
}
}
here is a part of logcat
There doesn't seem to be any reason to override onNewInent in your MainActivity.
In the onCreate() method use the following:
if(savedInstanceState == null){
Intent splashIntent = new Intent(this, SplashIntent.class);
startActivity(splashIntent);
}
This will start the splash screen whenever the MainActivity is initialized without a saved state. Since your SplashIntent activity calls finish after it is done it should revert to the last activity in the stack (aka your MainActivity).
An even better way to do this would be to use your SplashIntent activity as your launcher activity and then forward the user to the MainActivity using an intent.
Very simple example would be:
public class SplashIntent extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
log.debug("SplashIntent: onCreate");
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
log.debug("SplashIntent: killing splash");
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
finish();
}
}, splashTime);
}
}
Try startActivityForResult to launch splash screen (SplashIntent).
instead of
Intent intentSplash = new Intent(this, SplashIntent.class);
startActivity(intentSplash);
Try the below
startActivityForResult
And then from SplashIntent.java
Intent i = new Intent();
setResult(Activity.RESULT_OK,i); //pass your result
finish(); // Call finish to remove splash from the stack
Ref link :
http://developer.android.com/training/basics/intents/result.html
Sample code :
public class MainActivity extends Activity {
static final int SHOW_SPLASH_SCREEN_REQUEST = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
showSplashSCreen();
}
private void showSplashSCreen() {
Intent intentSplash = new Intent(this, SplashActivity.class);
startActivityForResult(intentSplash,
SHOW_SPLASH_SCREEN_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
// Check which request we're responding to
if (requestCode == SHOW_SPLASH_SCREEN_REQUEST) {
// Make sure the request was successful
if (resultCode == RESULT_OK) {
// code to handle anything after splash screen finished.
}
}
}
}
Splash Screen :
public class SplashActivity extends Activity {
private static final int splashTime = 3000;
#Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
// optional per your requirement
setResult(MainActivity.SHOW_SPLASH_SCREEN_REQUEST);
// must call finish
finish();
}
}, splashTime);
}
}