This is a read/scan NFC code.
I'm trying it out and I need it to work so that I would write my own code for another read activity.
The app keeps on crashing and the error is always, "There's a bug, please fix it for the app to start."
The source video/code was this link https://www.youtube.com/watch?v=QzphwRdJ7r0
Main Activity
package com.example.nfcreadscan;
import androidx.appcompat.app.AppCompatActivity;
import android.annotation.SuppressLint;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.IntentFilter;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.os.Bundle;
import android.os.Parcelable;
import android.widget.TextView;
import java.util.Arrays;
public class MainActivity extends AppCompatActivity {
private TextView textView;
private IntentFilter[] readfilters;
private PendingIntent pendingintent;
#SuppressLint("UnspecifiedImmutableFlag")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.text);
try {
Intent intent = new Intent (this, getClass());
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
pendingintent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
IntentFilter jdf = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
jdf.addDataScheme("http");
jdf.addDataAuthority("javadude.com", null);
IntentFilter jdt = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED,"text/plain");
readfilters = new IntentFilter[]{jdf, jdt};
} catch (IntentFilter.MalformedMimeTypeException e) {
e.printStackTrace();
}
processNFC(getIntent());
}
private void enableRead(){
NfcAdapter.getDefaultAdapter(this).enableForegroundDispatch(this,pendingintent, readfilters,null);
}
private void disableRead(){
NfcAdapter.getDefaultAdapter(this).disableForegroundDispatch(this);
}
#Override
protected void onResume(){
super.onResume();
enableRead();
}
#Override
protected void onPause(){
super.onPause();
disableRead();
}
#Override
protected void onNewIntent(Intent intent){
super.onNewIntent(intent);
processNFC(intent);
}
private void processNFC(Intent intent){
Parcelable[] messages = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
textView.setText("");
if(messages != null){
for(Parcelable message : messages){
NdefMessage ndefMessage = (NdefMessage) message;
for(NdefRecord record : ndefMessage.getRecords()) {
if (record.getTnf() == NdefRecord.TNF_WELL_KNOWN) {
textView.append("well known: ");
if (Arrays.equals(record.getType(), NdefRecord.RTD_TEXT)) {
textView.append("text: ");
textView.append(new String(record.getPayload()));
textView.append("\n");
} else if (Arrays.equals(record.getType(), NdefRecord.RTD_URI)) {
textView.append("uri");
textView.append(new String(record.getPayload()));
textView.append("\n");
}
}
}
}
}
}
}
Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.nfcreadscan">
<uses-permission android:name="android.permission.NFC"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/Theme.Nfcreadscan">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
<action android:name="android.intent.action.NDEF_DISCOVERED" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
</application>
</manifest>
Related
I'm new in this Android, and really stuck with it..
Never that was like that - on a start level and already stuck.
When register the Receiver class it returns Intent = null.. means it doesn't know anything about such request (Action, Intent)..
Tested on Nexus Emulator + Samsung device NOTE4.. same result.
Please, help me. What is a tricky thing I do not see yet?
General activity
public class MainActivity extends AppCompatActivity {
EventBroadcaster sms;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent ret;
sms = new EventBroadcaster();
sms.setMainActivity(this);
sms.say("Hello from EventBroadcaster");
IntentFilter filter = new IntentFilter();
filter.addAction("android.provider.Telephony.SMS_RECEIVED");
//filter.addCategory(Intent.CATEGORY_DEFAULT);
ret = registerReceiver(sms, filter);
//******************************************//
if (ret == null) {
sms.say("Fault to activate Broadcaster.. Intent = null");
}
}
public void showToast(String message){
// Show Alert
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(getApplicationContext(), message, duration);
toast.show();
}
}
BroadcastReceiver
public class EventBroadcaster extends BroadcastReceiver {
MainActivity ma;
public void setMainActivity(MainActivity context) {
ma = context;
say("MainActivity reference is received");
}
#Override
public void onReceive(Context context, Intent intent) {
say("Notification received");
}
public void say(String phrase){
ma.showToast(phrase);
}
}
Manifest
<manifest ...>
<uses-permission android:name="android.permission.RECEIVE_SMS"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
==============================================
So, after Vishnu answered, I think wouldn't be extra to place the working code of the
General Activity
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
import android.provider.Telephony;
public class MainActivity extends AppCompatActivity {
EventBroadcaster sms;
final int MY_PERMISSIONS_REQUEST_READ_SMS = 100;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sms = new EventBroadcaster();
sms.setMainActivity(this);
sms.say("Hello from EventBroadcaster");
if (VERSION.SDK_INT <= 23) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.RECEIVE_SMS},
MY_PERMISSIONS_REQUEST_READ_SMS);
}
else if (ContextCompat.checkSelfPermission(this,
Manifest.permission.RECEIVE_SMS) != PackageManager.PERMISSION_GRANTED ){
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.RECEIVE_SMS},
MY_PERMISSIONS_REQUEST_READ_SMS);
} else { /*Permission granted*/ }
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
Intent ret;
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_READ_SMS: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
IntentFilter filter = new IntentFilter();
filter.addAction("android.provider.Telephony.SMS_RECEIVED");
ret = registerReceiver(sms, filter);
if (ret != null) {
sms.say("Permission to READ SMS granted");
}
} else {
sms.say("Ooops, no permission to READ SMS");
}
return;
}
}
}
public void showToast(String message){
// Show Alert
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(getApplicationContext(), message, duration);
toast.show();
}
}
Apps targeting Android 6.0 and above need to handle the run-time permission.
Refer the Android documentation Requesting Permissions at Run Time
I think, this might be the reason.
try to declare receiver on your manifest
<receiver
android:name="com.example.EventBroadcaster"
android:exported="true" >
<intent-filter android:priority="1000" >
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
I am trying to build Whatsapp Notification filtering app, where I monitor all notification from Whatsapp and remove messages using some filter.
so can some one help me how to catch those notification messages so that I can manipulate them
I knew I have to use accessibility service but I am not able to get any event
all that i get is null source of event also null
https://stackoverflow.com/users/2452075/ghmulchandani
My codes are :- using accessibility service
MainActivity.java
package com.example.pavilion.accessebilityone;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
static TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView)findViewById(R.id.textView);
Intent intent = new Intent(android.provider.Settings.ACTION_ACCESSIBILITY_SETTINGS);
startActivityForResult(intent, 0);
Intent service = new Intent(this,WhatsappService.class);
startService(service);
}
}
Accessibility service class:-
import android.accessibilityservice.AccessibilityService;
import android.accessibilityservice.AccessibilityServiceInfo;
import android.app.Notification;
import android.os.Parcelable;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;
import android.view.accessibility.AccessibilityWindowInfo;
import android.widget.RemoteViews;
import android.widget.TextView;
import android.widget.Toast;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Created by pavilion on 6/6/2017.
*/
public class WhatsappService extends AccessibilityService {
protected void onServiceConnected() {
Toast.makeText(this, "connectd", Toast.LENGTH_SHORT).show();
AccessibilityServiceInfo info = new AccessibilityServiceInfo();
info.eventTypes = AccessibilityEvent.TYPE_NOTIFICATION_STATE_CHANGED;
info.feedbackType = AccessibilityServiceInfo.FEEDBACK_GENERIC;
info.notificationTimeout = 100;
setServiceInfo(info);
}
public synchronized void onAccessibilityEvent(AccessibilityEvent event) {
if (event.getEventType() == AccessibilityEvent.TYPE_NOTIFICATION_STATE_CHANGED) {
CharSequence pk = event.getPackageName();
//Toast.makeText(this,cl,Toast.LENGTH_SHORT).show();
Toast.makeText(this, pk, Toast.LENGTH_SHORT).show();
Notification n = (Notification) event.getParcelableData();
if (n == null)
return;
RemoteViews rv = n.contentView;
View view = rv.apply(this, null);
if (view == null)
return;
if (view instanceof ViewGroup) {
ViewGroup group = (ViewGroup) view;
searchTextView(group);
}
}
}
#Override
public void onInterrupt() {
}
private void searchTextView(ViewGroup group) {
int count = group.getChildCount();
for (int i = 0; i < count; i++) {
View v = group.getChildAt(i);
if (v instanceof TextView) {
Toast.makeText(this,((TextView) v).getText(),Toast.LENGTH_SHORT).show();
} else if (v instanceof ViewGroup) {
searchTextView((ViewGroup) v);
}
}
}
}
Manifest file:-
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.pavilion.accessebilityone">
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".WhatsappService"
android:enabled="true"
android:exported="true"
android:permission="android.permission.BIND_ACCESSIBILITY_SERVICE" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
<action android:name="android.accessibilityservice.AccessibilityService"/>
</intent-filter>
<meta-data android:name="android.accessibilityservice"
android:resource="#xml/accessibilityservice"/>
</service>
</application>
</manifest>
accessibility -service xml
<?xml version="1.0" encoding="utf-8"?>
<accessibility-service
android:accessibilityEventTypes="typeNotificationStateChanged"
android:accessibilityFeedbackType="feedbackGeneric"
android:canRetrieveWindowContent="true"
android:notificationTimeout="100"
android:settingsActivity="com.example.pavilion.accessebilityone.MainActivity"
xmlns:android="http://schemas.android.com/apk/res/android">
</accessibility-service>
You need to extend the notification listener service.
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
public class WhatsappNotifcationListener extends NotificationListenerService {
#Override
public IBinder onBind(Intent intent) {
return super.onBind(intent);
}
#Override
public void onNotificationPosted(StatusBarNotification statusBarNotification) {
String packageName = statusBarNotification.getPackageName();
Bundle extras = statusBarNotification.getNotification().extras;
if (extras.getCharSequence("android.text") == null) {
return;
}
String message = extras.getCharSequence("android.text").toString();
String notificationTitle = extras.getString(Notification.EXTRA_TITLE);
if (notificationTitle == null) {
return;
}
handleNotification(packageName, notificationTitle, message);
}
#Override
public void onNotificationRemoved(StatusBarNotification statusBarNotification) {
super.onNotificationRemoved(statusBarNotification);
}
private void handleNotification(String packageName, String notificationTitle, String message) {
if(!packageName.equalsIgnoreCase("whatsapp packagename"))){
return;
}
//Do something with notification title and notification message
}
}
To prompt the user to give notification access use the following from in an activity:
activity.startActivity(new Intent("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS"));
Ensure that you include the following in your manifest file within the tag:
<service
android:name=".WhatsappNotifcationListener"
android:enabled="true"
android:label="#string/app_name"
android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE">
<intent-filter>
<action android:name="android.service.notification.NotificationListenerService" />
</intent-filter>
</service>
No problems in first activity open on emulator but the problem is when press on the button it upon
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class MainlayoutActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mainlayout);
final Button man = (Button) findViewById(R.id.getDATA);
man.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MainlayoutActivity.this, second.class);
startActivityForResult(i, 77);
}
});
}
public void onActivityResult(int requstCode, int resultCode, Intent data) {
if ((requstCode == 77) && (resultCode == Activity.RESULT_OK)) {
String gett = data.getExtras().getString("TEXT value");
Toast.makeText(this, gett, Toast.LENGTH_LONG).show();
}
}
}
the problem is start second activity on emulator
public class second extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.seconlayout);
final Button btn = (Button) findViewById(R.id.GDATA);
final EditText ed = (EditText) findViewById(R.id.value);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String word = ed.getText().toString();
Intent i = new Intent();
i.putExtra("TEXT value", word);
setResult(Activity.RESULT_OK, i);
finish();
}
});
}
}
And the manifest file
<? xml version = "1.0"encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.l9"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk
android:minSdkVersion="15"
android:targetSdkVersion="15"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme">
<activity
android:name="com.example.l9.MainlayoutActivity"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<activity android:name="com.example.l9.second">
<intent-filter>
<action android:name="net.abdullaheid.action.ToDATA"/>
<category android:name="android.intent.categor.DEFAULT"/>
</intent-filter>
</activity>
</application>
</manifest>
Intent intent = new Intent();
This without parameters is useless if you dont want to transfer from this activity back. You need to create Intent with parameters
Intent(ThisActivity.this, WhereIWantToGoActivity.class) and then call startActivity(intent).
So, you got error, because your Intent() constructor is empty.
Guys have anybody got the ActivityrecognitionAPI to work in Android. It does not give any updates. Have tried the API documents, Plenty of Examples. OnHandleIntent does not fire.
import com.google.android.gms.location.ActivityRecognitionResult;
import com.google.android.gms.location.DetectedActivity;
import android.app.IntentService;
import android.content.Intent;
import android.support.v4.content.LocalBroadcastManager;
public class ActivityRecognitionIntentService extends IntentService{
ActivityRecognitionResult result;
Intent i;
DetectedActivity mpactivity;
public ActivityRecognitionIntentService() {
super("ActivityRecognitionIntentService");
i = new Intent("ACTIVITY_RECOGNITION_DATA");
}
private String getTypes(int type) {
if(type == DetectedActivity.UNKNOWN)
return "Unknown";
else if(type == DetectedActivity.IN_VEHICLE)
return "In Vehicle";
else if(type == DetectedActivity.ON_BICYCLE)
return "On Bicycle";
else if(type == DetectedActivity.RUNNING)
return "Running";
else if(type == DetectedActivity.ON_FOOT)
return "On Foot";
else if(type == DetectedActivity.STILL)
return "Still";
else if(type == DetectedActivity.TILTING)
return "Tilting";
else if(type == DetectedActivity.WALKING)
return "Walking";
else
return "";
}
#Override
protected void onHandleIntent(Intent intent) {
if (intent.getAction() == "ActivityRecognitionIntentService") {
if(ActivityRecognitionResult.hasResult(intent)){
result = ActivityRecognitionResult.extractResult(intent);
mpactivity = result.getMostProbableActivity();
i.putExtra("Activity", getTypes(mpactivity.getType()));
i.putExtra("Confidence", mpactivity.getConfidence());
LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(i);
}
}
}
}
The Main activity is as
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.ActivityRecognition;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.widget.TextView;
import android.widget.Toast;
public class Actrecogex extends Activity implements GooglePlayServicesClient.ConnectionCallbacks, GooglePlayServicesClient.OnConnectionFailedListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener{
TextView textView1;
GoogleApiClient mGoogleActclient;
PendingIntent mActivityRecognitionPendingIntent;
Intent i;
LocalBroadcastManager mBroadcastManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.actrecogex);
textView1 = new TextView(this);
textView1 =(TextView)findViewById(R.id.textView1);
i = new Intent(this, ActivityRecognitionIntentService.class);
mBroadcastManager = LocalBroadcastManager.getInstance(this);
mGoogleActclient = new GoogleApiClient.Builder(this)
.addApi(ActivityRecognition.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
mGoogleActclient.connect();
}
#Override
public void onConnectionFailed(ConnectionResult arg0) {
textView1.setText("Failed Connection" + arg0);
}
#Override
public void onConnected(Bundle arg0) {
i.setAction("ActivityRecognitionIntentService");
mActivityRecognitionPendingIntent = PendingIntent.getService(this, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);
ActivityRecognition.ActivityRecognitionApi.requestActivityUpdates(mGoogleActclient, 0, mActivityRecognitionPendingIntent);
}
#Override
public void onConnectionSuspended(int arg0) {
textView1.setText("Failed Suspended" + arg0);
}
private BroadcastReceiver receiver = new BroadcastReceiver(){
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(getApplicationContext(), "Service", Toast.LENGTH_SHORT).show();
String v = "Activity :" + intent.getStringExtra("Activity") + " " + "Confidence : " + intent.getExtras().getInt("Confidence") + "\n";
v += textView1.getText() ;
textView1.setText(v);
}
};
#Override
public void onDisconnected() {
textView1.setText("Disconnected" );
}
}
Manifest
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="21" />
<uses-permission android:name="com.google.android.gms.permission.ACTIVITY_RECOGNITION"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".Actrecogex"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<meta-data android:name="com.google.android.gms.version" android:value="#integer/google_play_services_version"/>
<service android:name="ActivityRecognitionIntentService" android:exported="false"></service>
</application>
Does the code really work, Or I am wasting time. Seriously want to go back Activityrecogntionclient. Testing the App on Gingerbread and Kitkat. Both does not budge
It seems your definition of the service in the Manifest is wrong: it is missing a leading period. It should be
<service android:name=".ActivityRecognitionIntentService" android:exported="false"></service>
Your onHandleIntent() uses
intent.getAction() == "ActivityRecognitionIntentService"
But you cannot compare strings with == so your if statement never returns true. Instead, you must use equals() or the equivalent TextUtils.equals() (which also handles cases where either argument is null):
"ActivityRecognitionIntentService".equals(intent.getAction())
// OR
TextUtils.equals(intent.getAction(), "ActivityRecognitionIntentService")
if (intent.getAction() == "ActivityRecognitionIntentService") {
}
Was giving null value. So the periodic Error Message.
The Main Problem was the Broadcastreceiver was not receiving anything. So needed to have separate class for Broadcastreceiver. It is Working now.
<receiver android:name="ActBreceiver" android:exported="false">
<intent-filter>
<action android:name="ACTIVITY_RECOGNITION_DATA"/>
</intent-filter>
</receiver>
I am trying to broadcast a toast message with the following code extending Activity. But the broadcast is not received by another Activity, the toast is not displayed. Can someone solve my error? The main activity is SendBroadcast.java
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
public class SendBroadcast extends Activity {
public static String BROADCAST_ACTION =
"com.unitedcoders.android.broadcasttest.SHOWTOAST";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void sendBroadcast(View v) {
Intent broadcast = new Intent();
broadcast.setAction(BROADCAST_ACTION);
sendBroadcast(broadcast);
}
}
Toast Display Activity is ToastDisplay.java
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.widget.Toast;
public class ToastDisplay extends Activity {
private BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(getApplicationContext(), "received",
Toast.LENGTH_SHORT).show();
}
};
#Override
protected void onResume() {
IntentFilter filter = new IntentFilter();
filter.addAction(SendBroadcast.BROADCAST_ACTION);
registerReceiver(receiver, filter);
super.onResume();
}
#Override
protected void onPause() {
unregisterReceiver(receiver);
super.onPause();
}
}
and manifest.xml is as follows
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.broad"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="3" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<activity
android:name=".SendBroadcast"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".ToastReceiver" >
<intent-filter>
<action android:name="com.unitedcoders.android.broadcasttest.SHOWTOAST" />
</intent-filter>
</receiver>
</application>
</manifest>
There can be two types of broacast: static and dynamic. Static are those that are declared in the manifest file. Dynamic can be declared during runtime. You combined these two types of broadcast in one broadcast.
To declare a simple dynamic broadcast you can use the following code (that is based on your code). It will simply display toast message when activity is shown.
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
public class BroadcastTestActivity extends Activity {
public static String BROADCAST_ACTION =
"com.unitedcoders.android.broadcasttest.SHOWTOAST";
BroadcastReceiver br = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Log.w("Check", "Inside On Receiver");
Toast.makeText(getApplicationContext(), "received",
Toast.LENGTH_SHORT).show();
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
IntentFilter filter = new IntentFilter();
filter.addAction(BROADCAST_ACTION);
filter.addCategory(Intent.CATEGORY_DEFAULT);
registerReceiver(br, filter);
}
#Override
protected void onResume() {
super.onResume();
sendBroadcast();
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(br);
}
public void sendBroadcast() {
Intent broadcast = new Intent();
broadcast.setAction(BROADCAST_ACTION);
broadcast.addCategory(Intent.CATEGORY_DEFAULT);
sendBroadcast(broadcast);
}
}
So now instead of showing toast you can call your new activity. The following actions depend on your needs (what you want to do).
Where is ToastReceiver class?
<receiver android:name=".ToastReceiver">
<intent-filter>
<action android:name="com.unitedcoders.android.broadcasttest.SHOWTOAST"/>
</intent-filter>
</receiver>`
Change
public class ToastDisplay extends Activity {
private BroadcastReceiver receiver = new BroadcastReceiver() {
}
to
public class ToastReceiver extends BroadcastReceiver {
}
Try
<activity android:name=".SendBroadcast" android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.BROADCAST" />
</intent-filter>
</activity>
In onCreate() call
sendBroadcast(v);
Button b1 = (Button)findViewById(R.id.button1);
b1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
try {
String RESULT = new TestAsyncTask().execute(" ").get();
System.out.println("RESULT "+RESULT);
}
catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});