I am Trying to start a service if the DetectedActivity returned from Activity recognition returned is IN_VEHICLE. I have downloaded a code sample
from :
http://tutsberry.com/activity-recognition-implementation-on-android/
But i'm not sure where to put code in to start my service.
I am Trying to the check the user activity in the background using the Activity Recognition and then
start a service all in the background.
ActivityRecognitionIntentService Class
public class ActivityRecognitionIntentService extends IntentService {
//LogCat
private static final String TAG = ActivityRecognitionIntentService.class.getSimpleName();
public ActivityRecognitionIntentService() {
super("ActivityRecognitionIntentService");
}
protected void onHandleIntent(Intent intent) {
if (ActivityRecognitionResult.hasResult(intent)) {
//Extract the result from the Response
ActivityRecognitionResult result = ActivityRecognitionResult.extractResult(intent);
DetectedActivity detectedActivity = result.getMostProbableActivity();
//Get the Confidence and Name of Activity
int confidence = detectedActivity.getConfidence();
String mostProbableName = getActivityName(detectedActivity.getType());
//Fire the intent with activity name & confidence
Intent i = new Intent("ImActive");
i.putExtra("activity", mostProbableName);
i.putExtra("confidence", confidence);
Log.d(TAG, "Most Probable Name : " + mostProbableName);
Log.d(TAG, "Confidence : " + confidence);
//Send Broadcast to be listen in MainActivity
this.sendBroadcast(i);
} else {
Log.d(TAG, "Intent had no data returned");
}
}
//Get the activity name
private String getActivityName(int type) {
switch (type) {
case DetectedActivity.IN_VEHICLE:
return "In Vehicle";
case DetectedActivity.ON_BICYCLE:
return "On Bicycle";
case DetectedActivity.ON_FOOT:
return "On Foot";
case DetectedActivity.WALKING:
return "Walking";
case DetectedActivity.STILL:
return "Still";
case DetectedActivity.TILTING:
return "Tilting";
case DetectedActivity.RUNNING:
return "Running";
case DetectedActivity.UNKNOWN:
return "Unknown";
}
return "N/A";
}
}
MainActivity Class
public class MainActivity extends Activity implements GoogleApiClient.ConnectionCallbacks,GoogleApiClient.OnConnectionFailedListener{
// LogCat
private static final String TAG = MainActivity.class.getSimpleName();
private Context mContext;
private GoogleApiClient mGApiClient;
private BroadcastReceiver receiver;
private TextView textView;
private TextView tv2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.msg);
textView.setMovementMethod(new ScrollingMovementMethod());
tv2 = (TextView) findViewById(R.id.text2);
//Set the context
mContext = this;
//Check Google Play Service Available
if (isPlayServiceAvailable()) {
mGApiClient = new GoogleApiClient.Builder(this)
.addApi(ActivityRecognition.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
//Connect to Google API
mGApiClient.connect();
} else {
Toast.makeText(mContext, "Google Play Service not Available", Toast.LENGTH_LONG).show();
}
//Broadcast receiver
receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
//Add current time
Calendar rightNow = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("h:mm:ss a");
String strDate = sdf.format(rightNow.getTime());
;
String v = strDate + " " +
intent.getStringExtra("activity") + " " +
"Confidence : " + intent.getExtras().getInt("confidence") + "\n";
v = textView.getText() + v;
textView.setText(v);
}
};
//Filter the Intent and register broadcast receiver
IntentFilter filter = new IntentFilter();
filter.addAction("ImActive");
registerReceiver(receiver, filter);
//Check for Google play services available on device
}
private boolean isPlayServiceAvailable() {
return GooglePlayServicesUtil.isGooglePlayServicesAvailable(mContext) == ConnectionResult.SUCCESS;
}
#Override
protected void onDestroy() {
super.onDestroy();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public void onConnected(Bundle bundle) {
Intent i = new Intent(this, ActivityRecognitionIntentService.class);
PendingIntent mActivityRecongPendingIntent = PendingIntent
.getService(this, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);
Log.d(TAG, "connected to ActivityRecognition");
ActivityRecognition.ActivityRecognitionApi.requestActivityUpdates(mGApiClient, 0, mActivityRecongPendingIntent);
//Update the TextView
textView.setText("Connected to Google Play Services \nWaiting for Active Recognition... \n");
}
#Override
public void onConnectionSuspended(int i) {
Log.d(TAG, "Suspended to ActivityRecognition");
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.d(TAG, "Not connected to ActivityRecognition");
//Disconnect and detach the receiver
mGApiClient.disconnect();
unregisterReceiver(receiver);
}
}
MainActivity.java
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
public class MainActivity extends Activity {
IntentFilter filter;
BroadcastReceiver mReceiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
filter = new IntentFilter();
mReceiver = new MyReceiver();
filter.addAction("IN_VEHICLE"); //Name the action what ever you need to.
filter.addAction("OTHER_ACTION");
filter.addAction("YET_ANOTHER_ACTION)");
registerReceiver(mReceiver, filter); //Register the receiver you define with the actions you want.
}
class MyReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if("IN_VEHICLE_RESPONSE".equals(intent.getAction())){
//Launch other activities here
Intent i = new Intent(getApplicationContext(), InVehicleActivity.class );
startActivity(i);
}else if("OTHER_ACTION_RESPONSE".equals(intent.getAction())){
//Launch desired activity
}else if("YET_ANOTHER_ACTION_RESPONSE".equals(intent.getAction())){
//Launch desired activity
}else{
//Handle unssuported actions
}
}
}
}
MyIntentService.java
import android.app.IntentService;
import android.content.Intent;
import android.os.Bundle;
public class MyIntentService extends IntentService {
Bundle extras;
public MyIntentService() {
super("MyIntentService");
}
#Override
protected void onHandleIntent(Intent intent) {
extras = intent.getExtras();
if("IN_VEHICLE".equals(intent.getAction())){
inVehicle(extras);
return;
}
if("OTHER_ACTION".equals(intent.getAction())){
//otheraction method
return;
}
if("YET_ANOTHER_ACTION".equals(intent.getAction())){
//yetanotheraction method
return;
}
}
private void inVehicle(Bundle extras) {
//do work
//do work
Intent intent = new Intent();
intent.setAction("IN_VEHICLE_RESPONSE");
//put all other desired stuff in intent
getApplicationContext().sendBroadcast(intent);
}
}
Don't forget to add your receiver to your manifest.
I would suggest that you start Activities from Activity not Service layer.
Related
I am developing the attendance system using Bluetooth that allow the user to scan Bluetooth to get the Bluetooth address and compare it with registered Bluetooth address. The problem is, it only scan and display the registered list of student but not listing the available Bluetooth and also not compare with the register Bluetooth address.
here is the code for BluetoothScanActivity
public class BluetoothScanActivity extends AppCompatActivity {
public static final String TAG = BluetoothScanActivity.class.getSimpleName();
BluetoothAdapter mBluetoothAdapter;
IntentFilter filter;
BroadcastReceiver mReceiver;
String name[];
ArrayList<String> macID;
Bundle scan_data;
int countScans=0;
int numCountScans;
int value;
RippleBackground rippleBackground;
String classID;
boolean selectDateCheck = false;
Date selectedDate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bluetooth_scan);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
{
Window window = getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
window.setStatusBarColor(ContextCompat.getColor(getBaseContext(), R.color.main_blue));
}
classID = getIntent().getStringExtra("Class ID");
numCountScans = getIntent().getIntExtra("Number Scans",3);
value = getIntent().getIntExtra("Value",1);
selectDateCheck = getIntent().getBooleanExtra("Manual Date",false);
selectedDate = (Date)getIntent().getSerializableExtra("Selected Date");
Toast.makeText(this, numCountScans + " " + value, Toast.LENGTH_LONG).show();
rippleBackground = (RippleBackground)findViewById(R.id.content);
int MY_PERMISSIONS_REQUEST_ACCESS_COARSE_LOCATION = 1;
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, MY_PERMISSIONS_REQUEST_ACCESS_COARSE_LOCATION);
init();
if(mBluetoothAdapter==null)
{
Toast.makeText(getApplicationContext(),"Your device doesn't support bluetooth!",Toast.LENGTH_SHORT).show();
finish();
}
else
{
if (!mBluetoothAdapter.isEnabled()) {
turnOnBT();
}
}
scan_data=new Bundle();
name=new String[100];
macID = new ArrayList<String>();
Log.d(TAG, "onCreate: ");
searchDevices();
}
private void turnOnBT() {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, 1);
}
public void init()
{
mBluetoothAdapter=BluetoothAdapter.getDefaultAdapter();
//Create a BroadCastReceiver for ACTION_FOUND
mReceiver=new BroadcastReceiver()
{
#Override
public void onReceive(Context context, Intent intent) {
String action=intent.getAction();
//When discovery finds a device
if(BluetoothDevice.ACTION_FOUND.equals((action)))
{
//Get the BluetoothDevice object from the Intent
BluetoothDevice device=intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
//Add the name and address to an array adapter to show in a ListView
if(!macID.contains(device.getAddress().toUpperCase()))
macID.add(device.getAddress().toUpperCase());
Toast.makeText(context,device.getName(),Toast.LENGTH_SHORT).show();
}
else if(BluetoothAdapter.ACTION_STATE_CHANGED.equals((action)))
{
if(mBluetoothAdapter.getState()== BluetoothAdapter.STATE_OFF) {
turnOnBT();
}
}
else if(BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals((action)))
{
if(countScans == numCountScans-1)
{
rippleBackground.stopRippleAnimation();
Intent in = new Intent(BluetoothScanActivity.this, MarkStudentsActivity.class);
in.putExtra("Class ID", classID);
in.putExtra("Value",value);
in.putStringArrayListExtra("MAC ID's", macID);
intent.putExtra("Manual Date",selectDateCheck);
intent.putExtra("Selected Date",selectedDate);
startActivity(in);
finish();
}
else
{
countScans++;
Log.d("Mark","" + countScans);
mBluetoothAdapter.startDiscovery();
}
}
}
};
filter=new IntentFilter();
filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
filter.addAction(BluetoothDevice.ACTION_FOUND);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(mReceiver, filter);
}
#Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
if(mBluetoothAdapter!=null)
mBluetoothAdapter.cancelDiscovery();
unregisterReceiver(mReceiver);
}
I have a Touch Mobile Computer with a barcode scanner.
I'm trying to write an application that scans a barcode and imports data from the DB into the device. In order to use the scanner I use a broadcast receiver.
On the scan activity screen, there are a few barcodes to scan. I set the intent to transfer information from which edittext the scan was performed (using putextra). The broadcast receiver receives the scan the action but the input of the putextra is not exist (The handle variable gets a null value [Attached picture]).
I would be happy to help with what I'm doing wrong.
Activity Class:
public class MoveItemActivity extends AppCompatActivity {
private EditText item;
private EditText to;
private boolean mIsRegisterReceiver = false;
private BroadcastReceiver mBarcodeReceiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_move_item);
item = (EditText) this.findViewById(R.id.itemInEditText);
item.setOnFocusChangeListener(mEditText);
to = (EditText) this.findViewById(R.id.toInEditText);
to.setOnFocusChangeListener(mEditText);
this.registerReceiver();
}
EditText.OnFocusChangeListener mEditText = new EditText.OnFocusChangeListener(){
#Override
public void onFocusChange(View v, boolean hasFocus) {
Intent intent = new Intent();
switch (v.getId()){
case R.id.itemInEditText:
if (!hasFocus){
new CheckItem(MoveItemActivity.this).execute(item.getText().toString());
break;
}
else {
intent.setAction(BarcodeControllerConstants.ACTION_BARCODE_OPEN);
intent.putExtra(BarcodeControllerConstants.EXTRA_HANDLE, "item");
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
sendBroadcast(intent);
break;
}
case R.id.toInEditText:
if (!hasFocus){
new CheckLocation().execute(to.getText().toString());
break;
}
else
{
intent.setAction(BarcodeControllerConstants.ACTION_BARCODE_OPEN);
intent.putExtra(BarcodeControllerConstants.EXTRA_HANDLE, "to");
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
sendBroadcast(intent);
break;
}
}
}
};
private void registerReceiver() {
if (mIsRegisterReceiver)
return;
IntentFilter filter = new IntentFilter();
filter.addAction(BarcodeControllerConstants.ACTION_BARCODE_CALLBACK_DECODING_DATA);
filter.addAction(BarcodeControllerConstants.ACTION_BARCODE_CALLBACK_REQUEST_SUCCESS);
filter.addAction(BarcodeControllerConstants.ACTION_BARCODE_CALLBACK_REQUEST_FAILED);
filter.addAction(BarcodeControllerConstants.ACTION_BARCODE_CALLBACK_GET_STATUS);
mBarcodeReceiver = new BarcodeController();
registerReceiver(mBarcodeReceiver, filter);
mIsRegisterReceiver = true;
}
BroadcastReceiver Class:
public class BarcodeController extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
int mBarcodeHandle = -1;
if (action.equals(BarcodeControllerConstants.ACTION_BARCODE_CALLBACK_DECODING_DATA)) {
String handle = intent.getExtras().getString(BarcodeControllerConstants.EXTRA_HANDLE);
byte[] data = intent.getByteArrayExtra(BarcodeControllerConstants.EXTRA_BARCODE_DECODING_DATA);
String result = null;
if (data != null) {
result = new String(data);
Intent i = new Intent(context, MoveItemActivity.class);
i.putExtra(handle,result );
context.startActivity(i);
}
} else if (action.equals(BarcodeControllerConstants.ACTION_BARCODE_CALLBACK_REQUEST_SUCCESS)) {
mBarcodeHandle = intent.getIntExtra(BarcodeControllerConstants.EXTRA_HANDLE, 0);
System.out.println("ACTION_BARCODE_CALLBACK_REQUEST_SUCCESS:" + mBarcodeHandle);
} else if (action.equals(BarcodeControllerConstants.ACTION_BARCODE_CALLBACK_REQUEST_FAILED)) {
int result = intent.getIntExtra(BarcodeControllerConstants.EXTRA_INT_DATA2, 0);
System.out.println("ACTION_BARCODE_CALLBACK_REQUEST_FAILED:" + result);
} else if (action.equals(BarcodeControllerConstants.ACTION_BARCODE_CALLBACK_GET_STATUS)) {
int status = intent.getIntExtra(BarcodeControllerConstants.EXTRA_INT_DATA2, 0);
System.out.println("ACTION_BARCODE_CALLBACK_GET_STATUS:" + status);
}
}
}
The item that you're sending in broadcast has action:
intent.setAction(BarcodeControllerConstants.ACTION_BARCODE_OPEN);
But in onReceive() you're checking different action:
action.equals(BarcodeControllerConstants.ACTION_BARCODE_CALLBACK_DECODING_DATA)
Are you sure this is the same intent that the one you're putting extras to?
intent.putExtra(BarcodeControllerConstants.EXTRA_HANDLE, "item");
You don't even register BarcodeControllerConstants.ACTION_BARCODE_OPEN action in your BarcodeController broadcast, so I think it's not received.
Purpose of program: I'm trying to make an app that will count how many times the user checked their phone by issuing a broadcast for Intent.ACTION_SCREEN_ON. it then increments a counter and updates the activity with the new counter.
The problem: This all works just fine but as soon as I swipe away the application from the apps tray, the counter goes back to zero.
obviously what is supposed to happen is the counter would continue.
I tried saving the counter value in the service onDestroy and then calling it again onCreate but onDestroy is never called.
Note that in the onCreate() for the activity it sends a broadcast to the service asking for the most recent value of counter and then updates it in the view. I couldn't find a better way to keep them in sync.
CounterService.java
public class CounterService extends Service {
public static boolean RERUN = true;
private int counter = 0;
private SharedPreferences SP;
private BroadcastReceiver mScreenStateBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
counter++;
System.out.println("************************************* \n \n " + counter);
}
sendCounterBroadcast();
}
};
public void sendCounterBroadcast() {
Intent i = new Intent();
i.setAction("com.inc.count");
i.putExtra("counterValue", counter);
sendBroadcast(i);
}
#Override
public void onCreate() {
super.onCreate();
System.out.println("********************** CounterService.onCreate()");
// get counter value from SP -- this is useful for when the service gets recreated
SP = getSharedPreferences("Counter Service Data", MODE_PRIVATE);
counter = SP.getInt("counter", 0);
// wait for screen to be turned on or for the activity to ask you for the counter number
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(Intent.ACTION_SCREEN_ON);
intentFilter.addAction("send.counter.to.phonecounteractivity");
registerReceiver(mScreenStateBroadcastReceiver, intentFilter);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return Service.START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
System.out.println("***************************************** CounterService.OnDestroy()");
unregisterReceiver(mScreenStateBroadcastReceiver);
// Save counter value for when we restart service
SP = getSharedPreferences("Counter Service Data", MODE_PRIVATE);
SharedPreferences.Editor SPE = SP.edit();
if (RERUN) {
SPE.putInt("counter", counter);
System.out.println("******************************** RESTARTING SERVICE ");
startService(new Intent(getApplicationContext(), CounterService.class));
} else
SPE.putInt("counter", 0);
SPE.apply();
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
PhoneCheckerCounter.Java
public class PhoneCheckerCounter extends AppCompatActivity {
private BroadcastReceiver changeCount;
private IntentFilter filter;
private int counter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_phone_checker_counter);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
switcherOnClick();
assignValuesOnCreate();
System.out.println("**************************** onCreate()");
changeCounterText();
}
public void switcherOnClick() {
final Switch sCounter = findViewById(R.id.switchCounter);
sCounter.setOnClickListener(new View.OnClickListener() {
Intent intent = new Intent(getApplicationContext(), CounterService.class);
#Override
public void onClick(View v) {
if (sCounter.isChecked()) {
startService(intent);
CounterService.RERUN = true;
v.getContext().registerReceiver(changeCount, filter);
Toast.makeText(getApplicationContext(), "Counting has begun", Toast.LENGTH_SHORT).show();
} else {
TextView n = findViewById(R.id.counter);
n.setText("0");
CounterService.RERUN = false;
v.getContext().unregisterReceiver(changeCount);
stopService(intent);
Toast.makeText(getApplicationContext(), "The application stopped counting", Toast.LENGTH_SHORT).show();
}
}
});
}
public void changeCounterText() {
changeCount = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
TextView n = findViewById(R.id.counter);
counter = intent.getIntExtra("counterValue", 0);
System.out.println("************************ RECEIVED!!!! value of: " + counter);
n.setText("" + counter);
}
};
filter = new IntentFilter();
filter.addAction("com.inc.count");
this.registerReceiver(changeCount, filter);
}
#Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(changeCount);
assignValuesOnDestroy();
System.out.println("**************************** onDestroy()");
}
public void assignValuesOnCreate() {
Switch s = findViewById(R.id.switchCounter);
if (getSwitchValueFromSP() == 1) s.setChecked(true);
else s.setChecked(false);
Intent f = new Intent();
f.setAction("send.counter.to.phonecounteractivity");
sendBroadcast(f);
}
public void assignValuesOnDestroy() {
SharedPreferences SP = getSharedPreferences("data", MODE_PRIVATE);
SharedPreferences.Editor edit = SP.edit();
Switch s = findViewById(R.id.switchCounter);
if (s.isChecked()) edit.putInt("switch", 1);
else edit.putInt("switch", 0);
edit.apply();
}
public int getSwitchValueFromSP() {
SharedPreferences SP = getSharedPreferences("data", MODE_PRIVATE);
int isOn = SP.getInt("switch", 0);
return isOn;
}
}
Sample of the activity
i try almost code in the internet, but i can't solve it.
i want to send data from specific method in the service to activity.
i use intent(putExtra), but it doesn't go to activity class.
here is my RecoBackgroundRangingService.java
(i omit unnecessary code)
private static final String TAG = "RecoBackgroundRangingService";
public static final String BROADCAST_ACTION = "com.example.hello ";
private final Handler handler = new Handler();
Intent intent;
int counter = 0;
#Override
public void onCreate() {
Log.i("BackRangingService", "onCreate()");
super.onCreate();
intent = new Intent(BROADCAST_ACTION);
Toast.makeText(getBaseContext(),"on create", Toast.LENGTH_SHORT).show();
}
#Override
public void didEnterRegion(RECOBeaconRegion region, Collection<RECOBeacon> beacons) {
/**
* For the first run, this callback method will not be called.
* Please check the state of the region using didDetermineStateForRegion() callback method.
*
//Get the region and found beacon list in the entered region
Log.i("BackRangingService", "didEnterRegion() - " + region.getUniqueIdentifier());
this.popupNotification("Inside of " + region.getUniqueIdentifier());
//Write the code when the device is enter the region
DisplayLoggingInfo();
Toast.makeText(getBaseContext(),"did enter region", Toast.LENGTH_SHORT).show();
//this.startRangingWithRegion(region); //start ranging to get beacons inside of the region
//from now, stop ranging after 10 seconds if the device is not exited
}
private void DisplayLoggingInfo() {
//Log.d(TAG, "entered DisplayLoggingInfo");
//intent.putExtra("time", new Date().toLocaleString());
//intent.putExtra("counter", String.valueOf(++counter));
intent.putExtra("status", 1);
sendBroadcast(intent);
Toast.makeText(getBaseContext(),"display logging", Toast.LENGTH_SHORT).show();
}
here is my CheckActivity.java
(when i receive data, my purpose is that store data to the server. therefore, i don't need to use layout. So, in order to check data, i use toast "hello". but toast never popup my phone...)
public class CheckActivity extends Activity {
private static final String TAG = "CheckActivity";
private Intent intent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_check);
intent = new Intent(this, RecoBackgroundRangingService.class);
Toast.makeText(getBaseContext(), "check activity", Toast.LENGTH_SHORT).show();
}
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
updateUI(intent);
}
};
#Override
public void onResume() {
super.onResume();
startService(intent);
registerReceiver(broadcastReceiver, new IntentFilter(RecoBackgroundRangingService.BROADCAST_ACTION));
}
#Override
public void onPause() {
super.onPause();
unregisterReceiver(broadcastReceiver);
stopService(intent);
}
private void updateUI(Intent intent) {
int status = intent.getIntExtra("status", -1);
Toast.makeText(getBaseContext(), "hello", Toast.LENGTH_SHORT).show();
}
}
I've been trying to learn how to use notifications in Android by creating an application that creates, displays, and deletes notifications with button clicks (to clarify it will display the notifications in app). Now I can easily get my program to create notifications but when I try to delete the notification or display it I keep getting nulls and when I change the code up nothing. I found a few tutorials that helped me understand what I should be doing but the code they wrote did not work and I've hit a wall at this point. Here is my main activity:
public class MainActivity extends Activity {
private TextView txtView;
private NotificationReceiver nReceiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtView = (TextView) findViewById(R.id.textView);
nReceiver = new NotificationReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction("com.testing.notify.NOTIFICATION");
registerReceiver(nReceiver,filter);
}
#Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(nReceiver);
}
public void buttonClicked(View v){
if(v.getId() == R.id.btnCreateNotify){
NotificationManager nManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
NotificationCompat.Builder ncomp = new NotificationCompat.Builder(this);
ncomp.setSmallIcon(R.mipmap.ic_launcher);
ncomp.setContentTitle("Notify");
ncomp.setContentText("Notification Listener Service Example");
ncomp.setTicker("Notification Listener Service Example");
ncomp.setAutoCancel(true);
nManager.notify((int)System.currentTimeMillis(),ncomp.build());
}
else if(v.getId() == R.id.btnClearNotify){
Intent i = new Intent("com.testing.notify.NOTIFICATION");
i.putExtra("command","clearall");
sendBroadcast(i);
}
else if(v.getId() == R.id.btnListNotify){
Intent i = new Intent("com.testing.notify.NOTIFICATION");
i.putExtra("command","list");
sendBroadcast(i);
}
}
class NotificationReceiver extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
String temp = intent.getStringExtra("notification_event") + "n" + txtView.getText();
txtView.setText(temp);
}
}
And here is the code to my notification service class
public class NotificationService extends NotificationListenerService {
private String TAG = this.getClass().getSimpleName();
private NLServiceReceiver nlservicereceiver;
#Override
public void onCreate() {
super.onCreate();
nlservicereceiver = new NLServiceReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction("com.testing.notify.NOTIFICATION");
registerReceiver(nlservicereceiver,filter);
}
#Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(nlservicereceiver);
}
#Override
public void onNotificationPosted(StatusBarNotification sbn) {
Log.i(TAG,"********** onNotificationPosted");
Log.i(TAG,"ID :" + sbn.getId() + "t" + sbn.getNotification().tickerText + "t" + sbn.getPackageName());
Intent i = new Intent("com.testing.notify.NOTIFICATION");
i.putExtra("notification_event","onNotificationPosted :" + sbn.getPackageName() + "n");
sendBroadcast(i);
}
#Override
public void onNotificationRemoved(StatusBarNotification sbn) {
Log.i(TAG,"********** onNotificationRemoved");
Log.i(TAG,"ID :" + sbn.getId() + "t" + sbn.getNotification().tickerText +"t" + sbn.getPackageName());
Intent i = new Intent("com.testing.notify.NOTIFICATION");
i.putExtra("notification_event","onNotificationRemoved :" + sbn.getPackageName() + "n");
sendBroadcast(i);
}
class NLServiceReceiver extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
if(intent.getStringExtra("command").equals("clearall")){
NotificationManager notifManager= (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notifManager.cancelAll();
}
else if(intent.getStringExtra("command").equals("list")){
Intent i1 = new Intent("com.testing.notify.NOTIFICATION");
i1.putExtra("notification_event","=====================");
sendBroadcast(i1);
int i=1;
for (StatusBarNotification sbn : NotificationService.this.getActiveNotifications()) {
Intent i2 = new Intent("com.testing.notify.NOTIFICATION");
i2.putExtra("notification_event",i +" " + sbn.getPackageName() + "n");
sendBroadcast(i2);
i++;
}
Intent i3 = new Intent("com.testing.notify.NOTIFICATION");
i3.putExtra("notification_event","===== Notification List ====");
sendBroadcast(i3);
}
}
}
I've been trying to figure this out for a while now so any help would be appreciated.