I'm attempting to find the string or long values in my source code which return data (so I can post them to my server) however when I attempt to null check them using the following:
Log.d(TAG, String.valueOf(WifiInfo.LINK_SPEED_UNITS));
The data never appears in the logs. Any suggestions are greatly appreciated!
SERVICE CLASS SOURCE:
public class Service_class extends Service {
public static String TAG="TEST TAG";
TextView textSsid, textSpeed, textRssi;
public Handler mHandler = new Handler();
public long mStartRX = 0;
public long mStartTX = 0;
public long txBytes;
public void onCreate(Bundle savedInstanceState) {
super.onCreate();
textSsid = (TextView) findViewById(R.id.Ssid);
textSpeed = (TextView) findViewById(R.id.Speed);
textRssi = (TextView) findViewById(R.id.Rssi);
Long.toString(mStartTX);
Long.toString(mStartRX);
Long.toString(txBytes);
mStartRX = TrafficStats.getTotalRxBytes();
mStartTX = TrafficStats.getTotalTxBytes();
if (mStartRX == TrafficStats.UNSUPPORTED || mStartTX == TrafficStats.UNSUPPORTED) {
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Uh Oh!");
alert.setMessage("Your device does not support traffic stat monitoring.");
alert.show();
} else {
mHandler.postDelayed(mRunnable, 1000);
}
}
private TextView findViewById(int speed) {
// TODO Auto-generated method stub
return null;
}
private final Runnable mRunnable = new Runnable() {
public void run() {
TextView RX = (TextView)findViewById(R.id.RX);
TextView TX = (TextView)findViewById(R.id.TX);
long rxBytes = TrafficStats.getTotalRxBytes()- mStartRX;
RX.setText(Long.toString(rxBytes));
long txBytes = TrafficStats.getTotalTxBytes()- mStartTX;
TX.setText(Long.toString(txBytes));
mHandler.postDelayed(mRunnable, 1000);
ParseObject testObject = new ParseObject("TestObject");
testObject.put("DataOut", Long.valueOf(txBytes));
testObject.put("DataIn", Long.valueOf(mStartRX));
testObject.put("DataRSSI", String.valueOf(textRssi));
testObject.put("DataSpeed", String.valueOf(textSpeed));
testObject.saveInBackground();
final Chronometer myChronometer = (Chronometer)findViewById(R.id.chronometer);
myChronometer.start();
DisplayWifiState();
this.registerReceiver(this.myWifiReceiver, new IntentFilter(
ConnectivityManager.CONNECTIVITY_ACTION));
}
private Chronometer findViewById(int chronometer) {
// TODO Auto-generated method stub
return null;
}
private void registerReceiver(BroadcastReceiver myWifiReceiver2,
IntentFilter intentFilter) {
// TODO Auto-generated method stub
}
private BroadcastReceiver myWifiReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context arg0, Intent arg1) {
// TODO Auto-generated method stub
NetworkInfo networkInfo = (NetworkInfo) arg1
.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
DisplayWifiState();
}
}
};
public void DisplayWifiState() {
ConnectivityManager myConnManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo myNetworkInfo = myConnManager
.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
WifiManager myWifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiInfo myWifiInfo = myWifiManager.getConnectionInfo();
if (myNetworkInfo.isConnected()) {
textSsid.setText(myWifiInfo.getSSID());
textSpeed.setText(String.valueOf(myWifiInfo.getLinkSpeed()) + " "
+ WifiInfo.LINK_SPEED_UNITS);
Log.d(TAG, String.valueOf(WifiInfo.LINK_SPEED_UNITS));
textRssi.setText(String.valueOf(myWifiInfo.getRssi()));
} else {
textSsid.setText("---");
textSpeed.setText("---");
textRssi.setText("---");
}}};
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "Hello World", Toast.LENGTH_LONG).show();
// Log.d(TAG, "starting service");
ParseObject testObject = new ParseObject("TestObject");
testObject.put("DataOut", Long.valueOf(txBytes));
testObject.put("DataIn", Long.valueOf(mStartRX));
testObject.put("DataRSSI", String.valueOf(textRssi));
testObject.put("DataSpeed", String.valueOf(textSpeed));
testObject.saveInBackground();
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service Stopped", Toast.LENGTH_LONG).show();
}
#Override
public void onCreate() {
super.onCreate();
}
}
MAIN.Java
public class Main extends Activity {
TextView textSsid, textSpeed, textRssi;
public Handler mHandler = new Handler();
public long mStartRX = 0;
public long mStartTX = 0;
public long txBytes;
public static String TAG="TEST TAG";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Start service using AlarmManager
Calendar cal = Calendar.getInstance();
cal.add(Calendar.SECOND, 10);
Intent intent = new Intent(Main.this, Service_class.class);
PendingIntent pintent = PendingIntent.getService(Main.this, 0, intent,
0);
AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
12 * 1000, pintent);
// click listener for the button to start service
Button btnStart = (Button) findViewById(R.id.button1);
btnStart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startService(new Intent(getBaseContext(), Service_class.class));
}
});
// click listener for the button to stop service
Button btnStop = (Button) findViewById(R.id.button2);
btnStop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
stopService(new Intent(getBaseContext(), Service_class.class));
}
});
textSsid = (TextView) findViewById(R.id.Ssid);
textSpeed = (TextView) findViewById(R.id.Speed);
textRssi = (TextView) findViewById(R.id.Rssi);
Long.toString(mStartTX);
Long.toString(mStartRX);
Long.toString(txBytes);
ParseAnalytics.trackAppOpened(getIntent());
mStartRX = TrafficStats.getTotalRxBytes();
mStartTX = TrafficStats.getTotalTxBytes();
if (mStartRX == TrafficStats.UNSUPPORTED || mStartTX == TrafficStats.UNSUPPORTED) {
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Uh Oh!");
alert.setMessage("Your device does not support traffic stat monitoring.");
alert.show();
} else {
mHandler.postDelayed(mRunnable, 1000);
}}
private final Runnable mRunnable = new Runnable() {
public void run() {
TextView RX = (TextView)findViewById(R.id.RX);
TextView TX = (TextView)findViewById(R.id.TX);
long rxBytes = TrafficStats.getTotalRxBytes()- mStartRX;
RX.setText(Long.toString(rxBytes));
long txBytes = TrafficStats.getTotalTxBytes()- mStartTX;
TX.setText(Long.toString(txBytes));
mHandler.postDelayed(mRunnable, 1000);
final Chronometer myChronometer = (Chronometer)findViewById(R.id.chronometer);
myChronometer.start();
DisplayWifiState();
this.registerReceiver(this.myWifiReceiver, new IntentFilter(
ConnectivityManager.CONNECTIVITY_ACTION));
}
private void registerReceiver(BroadcastReceiver myWifiReceiver2,
IntentFilter intentFilter) {
// TODO Auto-generated method stub
}
private BroadcastReceiver myWifiReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context arg0, Intent arg1) {
// TODO Auto-generated method stub
NetworkInfo networkInfo = (NetworkInfo) arg1
.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
DisplayWifiState();
}
}
};
public void DisplayWifiState() {
ConnectivityManager myConnManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo myNetworkInfo = myConnManager
.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
WifiManager myWifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiInfo myWifiInfo = myWifiManager.getConnectionInfo();
if (myNetworkInfo.isConnected()) {
textSsid.setText(myWifiInfo.getSSID());
textSpeed.setText(String.valueOf(myWifiInfo.getLinkSpeed()) + " "
+ WifiInfo.LINK_SPEED_UNITS);
textRssi.setText(String.valueOf(myWifiInfo.getRssi()));
} else {
textSsid.setText("---");
textSpeed.setText("---");
textRssi.setText("---");
}
};
};}
you may add one string(any dummy) value so that they will appear, i think
Log.d(TAG,"Null: "+String.valueOf(WifiInfo.LINK_SPEED_UNITS));
Related
I created an application which pairs a cellphone to a bluetooth module.
i tested this application with a 4.2 android cellphone and it worked quite well but in cellphones with android higher than 6 the device is not fidning anything when i press " Scan for new devices " button.
but when i go through my phone bluetooth itself, i can find the module i was looking for..
Bluetooth connection class :
public class BluetoothConnectionActivity extends AppCompatActivity {
private ProgressDialog mProgressDlg;
private ArrayList<BluetoothDevice> mDeviceList = new ArrayList<BluetoothDevice>();
private BluetoothAdapter mBluetoothAdapter;
BluetoothDevice device ;
private MediaPlayer mediaplayer = null ;
private Button bluetoothOnOff;
private Button viewpairedDevices;
private Button scanfornewDevices;
private Button blue2;
ImageView unMute;
View view1;
View view2;
private Activity context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.bluetoothconnectionlayout);
bluetoothOnOff = (Button) findViewById(R.id.bluetoothOnOff);
viewpairedDevices = (Button) findViewById(R.id.viewpairedDevicesButton);
scanfornewDevices = (Button) findViewById(R.id.scanfornewDevicesButton);
blue2 = (Button) findViewById(R.id.bluetoothOnOff2);
view1 = findViewById(R.id.viewFader);
view2 = findViewById(R.id.viewFader2);
unMute = (ImageView) findViewById(R.id.settingStartupSecondary);
mediaplayer = MediaPlayer.create(getApplicationContext(),R.raw.sfxturnon);
Handler startup1 = new Handler();
startup1.postDelayed(new Runnable() {
#Override
public void run() {
view1.animate().alpha(1f).setDuration(500);
view2.animate().alpha(1f).setDuration(500);
}
},1000);
Handler startup2 = new Handler();
startup2.postDelayed(new Runnable() {
#Override
public void run() {
bluetoothOnOff.animate().alpha(1f).setDuration(500);
viewpairedDevices.animate().alpha(1f).setDuration(500);
scanfornewDevices.animate().alpha(1f).setDuration(500);
unMute.animate().alpha(1f).setDuration(100);
}
},1000);
//
// settingBtn.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View view) {
//
//
// AudioManager amanager=(AudioManager)getSystemService(Context.AUDIO_SERVICE);
// amanager.setStreamMute(AudioManager.STREAM_NOTIFICATION, true);
//
//// settingBtn.setEnabled(false);
//// settingBtn.animate().alpha(0f);
//
// unMute.animate().alpha(1f);
// unMute.setEnabled(true);
//
//
// Toast.makeText(getApplicationContext(), " Application muted. ", Toast.LENGTH_SHORT).show();
//
//
// }
// });
Handler dawg = new Handler();
dawg.postDelayed(new Runnable() {
#Override
public void run() {
bluetoothOnOff.animate().alpha(1f).setDuration(1500);
viewpairedDevices.animate().alpha(1f).setDuration(2500);
scanfornewDevices.animate().alpha(1f).setDuration(3000);
}
},500);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
mProgressDlg = new ProgressDialog(this);
mProgressDlg.setMessage("Scanning, Please wait...");
mProgressDlg.setCancelable(false);
mProgressDlg.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
mBluetoothAdapter.cancelDiscovery();
}
});}
if (mBluetoothAdapter.isEnabled()){
bluetoothOnOff.setText("Bluetooth is On");
blue2.setText("Bluetooth is On");
}else {
blue2.setText("Bluetooth is Off");
bluetoothOnOff.setText("Bluetooth is Off");
}
if (mBluetoothAdapter == null) {
showUnsupported();
} else {
viewpairedDevices.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
if (pairedDevices == null || pairedDevices.size() == 0) {
Toast toast = Toast.makeText(getApplicationContext()," No paired device found.", Toast.LENGTH_SHORT);
View view3 = toast.getView();
view3.setBackgroundColor(Color.parseColor("#ffff5b"));
TextView text = (TextView) view3.findViewById(android.R.id.message);
text.setTextColor(Color.parseColor("#000000"));
toast.show();
} else {
ArrayList<BluetoothDevice> list = new ArrayList<BluetoothDevice>();
list.addAll(pairedDevices);
Intent intent = new Intent(BluetoothConnectionActivity.this, DeviceList.class);
intent.putParcelableArrayListExtra("device.list", list);
startActivity(intent);
}
}
});
scanfornewDevices.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
mBluetoothAdapter.startDiscovery();
}
});
bluetoothOnOff.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (mBluetoothAdapter.isEnabled()) {
mBluetoothAdapter.disable();
showDisabled();
bluetoothOnOff.setText("Bluetooth is OFF");
final Handler handler6 = new Handler();
handler6.postDelayed(new Runnable() {
#Override
public void run() {
mediaplayer.start();
}
}, 500);
final Handler handler3 = new Handler();
handler3.postDelayed(new Runnable() {
#Override
public void run() {
bluetoothOnOff.animate().translationY(-1f).setDuration(5000);
blue2.animate().translationY(-1f).setDuration(5000);
bluetoothOnOff.animate().alpha(1f).setDuration(3000);
blue2.animate().alpha(0f).setDuration(3000);
}
}, 500);
} else {
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(intent, 1000);
}}
});
blue2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (mBluetoothAdapter.isEnabled()) {
mBluetoothAdapter.disable();
showDisabled();
bluetoothOnOff.setText("Bluetooth is OFF");
final Handler handler6 = new Handler();
handler6.postDelayed(new Runnable() {
#Override
public void run() {
mediaplayer.start();
}
}, 500);
final Handler handler3 = new Handler();
handler3.postDelayed(new Runnable() {
#Override
public void run() {
bluetoothOnOff.animate().translationY(-1f).setDuration(5000);
blue2.animate().translationY(-1f).setDuration(5000);
bluetoothOnOff.animate().alpha(1f).setDuration(3000);
blue2.animate().alpha(0f).setDuration(3000);
}
}, 500);
} else {
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(intent, 1000);
}}
});
if (mBluetoothAdapter.isEnabled()) {
showEnabled();
} else {
showDisabled();
}
}
IntentFilter 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
public void onPause() {
if (mBluetoothAdapter != null) {
if (mBluetoothAdapter.isDiscovering()) {
mBluetoothAdapter.cancelDiscovery();
}
}
super.onPause();
}
#Override
public void onBackPressed() {
}
#Override
public void onDestroy() {
unregisterReceiver(mReceiver);
super.onDestroy();
}
private void showEnabled() {
bluetoothOnOff.setEnabled(true);
viewpairedDevices.setEnabled(true);
viewpairedDevices.setBackgroundResource(R.drawable.selectorstylish);
scanfornewDevices.setEnabled(true);
scanfornewDevices.setBackgroundResource(R.drawable.selectorstylish);
}
private void showDisabled() {
bluetoothOnOff.setEnabled(true);
viewpairedDevices.setEnabled(false);
viewpairedDevices.setBackgroundResource(R.drawable.selectorstylish);
scanfornewDevices.setEnabled(false);
scanfornewDevices.setBackgroundResource(R.drawable.selectorstylish);
}
private void showUnsupported() {
Toast toast = Toast.makeText(getApplicationContext()," Bluetooth is not supported by this device.", Toast.LENGTH_SHORT);
View view3 = toast.getView();
view3.setBackgroundColor(Color.parseColor("#ffff5b"));
TextView text = (TextView) view3.findViewById(android.R.id.message);
text.setTextColor(Color.parseColor("#000000"));
toast.show();
bluetoothOnOff.setEnabled(false);
viewpairedDevices.setEnabled(false);
viewpairedDevices.setBackgroundResource(R.drawable.selectorstylish);
scanfornewDevices.setEnabled(false);
scanfornewDevices.setBackgroundResource(R.drawable.selectorstylish);
}
private void showToast(String message) {
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
}
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {
final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR);
if (state == BluetoothAdapter.STATE_ON) {
bluetoothOnOff.setText("Bluetooth is On");
blue2.setText("Bluetooth is On");
showEnabled();
final Handler handler5 = new Handler();
handler5.postDelayed(new Runnable() {
#Override
public void run() {
mediaplayer.start();
}
}, 500);
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
bluetoothOnOff.animate().translationY(150f).setDuration(5000);
blue2.animate().translationY(150f).setDuration(5000);
bluetoothOnOff.animate().alpha(0f).setDuration(3000);
blue2.animate().alpha(1f).setDuration(3000);
}
}, 500);
}
} else if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
mDeviceList = new ArrayList<BluetoothDevice>();
mProgressDlg.show();
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
mProgressDlg.dismiss();
// Intent newIntent = new Intent(BluetoothConnectionActivity.this, DeviceList.class);
//
// newIntent.putParcelableArrayListExtra("device.list", mDeviceList);
//
// startActivity(newIntent);
} else if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = (BluetoothDevice) intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
mDeviceList.add(device);
Toast toast = Toast.makeText(getApplicationContext()," Found device" + device.getName(), Toast.LENGTH_SHORT);
View view3 = toast.getView();
view3.setBackgroundColor(Color.parseColor("#ffff5b"));
TextView text = (TextView) view3.findViewById(android.R.id.message);
text.setTextColor(Color.parseColor("#000000"));
toast.show();
}
}
};
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.optionmenu,menu);
return super.onCreateOptionsMenu(menu);
}
}
Device list Class :
public class DeviceList extends AppCompatActivity {
private ListView mListView;
private AdapterClassBluetooth mAdapterClassBluetooth;
private ArrayList<BluetoothDevice> mDeviceList;
private BluetoothDevice device ;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_device_list);
mDeviceList = getIntent().getExtras().getParcelableArrayList("device.list");
mListView = (ListView) findViewById(R.id.lv_paired);
mAdapterClassBluetooth = new AdapterClassBluetooth(this);
mAdapterClassBluetooth.setData(mDeviceList);
mAdapterClassBluetooth.setListener(new AdapterClassBluetooth.OnPairButtonClickListener() {
#Override
public void onPairButtonClick(int position) {
BluetoothDevice device = mDeviceList.get(position);
if (device.getBondState() == BluetoothDevice.BOND_BONDED) {
unpairDevice(device);
} else {
Toast toast = Toast.makeText(getApplicationContext(), "Pairing..." , Toast.LENGTH_SHORT);
View view = toast.getView();
view.setBackgroundColor(Color.parseColor("#ffff5b"));
TextView text = (TextView) view.findViewById(android.R.id.message);
text.setTextColor(Color.parseColor("#000000"));
toast.show();
pairDevice(device);
}
}
});
mListView.setAdapter(mAdapterClassBluetooth);
registerReceiver(mPairReceiver, new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED));
}
#Override
public void onDestroy() {
unregisterReceiver(mPairReceiver);
super.onDestroy();
}
private void showToast(String message) {
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
}
private void pairDevice(BluetoothDevice device) {
try {
Method method = device.getClass().getMethod("createBond", (Class[]) null);
method.invoke(device, (Object[]) null);
} catch (Exception e) {
e.printStackTrace();
}
}
private void unpairDevice(BluetoothDevice device) {
try {
Method method = device.getClass().getMethod("removeBond", (Class[]) null);
method.invoke(device, (Object[]) null);
} catch (Exception e) {
e.printStackTrace();
}
}
private final BroadcastReceiver mPairReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) {
final int state = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, BluetoothDevice.ERROR);
final int prevState = intent.getIntExtra(BluetoothDevice.EXTRA_PREVIOUS_BOND_STATE, BluetoothDevice.ERROR);
if (state == BluetoothDevice.BOND_BONDED && prevState == BluetoothDevice.BOND_BONDING) {
Toast toast = Toast.makeText(getApplicationContext()," Device are paired, please wait...", Toast.LENGTH_SHORT);
View view = toast.getView();
view.setBackgroundColor(Color.parseColor("#ffff5b"));
TextView text = (TextView) view.findViewById(android.R.id.message);
text.setTextColor(Color.parseColor("#000000"));
toast.show();
Handler delaying = new Handler();
delaying.postDelayed(new Runnable() {
#Override
public void run() {
Intent communicate = new Intent(DeviceList.this,Security.class);
startActivity(communicate);
finish();
}
},1500);
} else if (state == BluetoothDevice.BOND_NONE && prevState == BluetoothDevice.BOND_BONDED){
Toast toast = Toast.makeText(getApplicationContext(),"Unpaired.", Toast.LENGTH_SHORT);
View view = toast.getView();
view.setBackgroundColor(Color.parseColor("#ffff5b"));
TextView text = (TextView) view.findViewById(android.R.id.message);
text.setTextColor(Color.parseColor("#000000"));
toast.show();
}
mAdapterClassBluetooth.notifyDataSetChanged();
}
}
};}
Adapter class :
public class AdapterClassBluetooth extends BaseAdapter{
private LayoutInflater mInflater;
private List<BluetoothDevice> mData;
private OnPairButtonClickListener mListener;
public AdapterClassBluetooth(){
}
public AdapterClassBluetooth(Context context) {
super();
mInflater = LayoutInflater.from(context);
}
public void setData(List<BluetoothDevice> data) {
mData = data;
}
public void setListener(OnPairButtonClickListener listener) {
mListener = listener;
}
public int getCount() {
return (mData == null) ? 0 : mData.size();
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.adapterlist, null);
holder = new ViewHolder();
holder.nameTv = (TextView) convertView.findViewById(R.id.tv_name);
holder.addressTv = (TextView) convertView.findViewById(R.id.tv_address);
holder.pairBtn = (Button) convertView.findViewById(R.id.btn_pair);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
BluetoothDevice device = mData.get(position);
holder.nameTv.setText(device.getName());
holder.addressTv.setText(device.getAddress());
holder.pairBtn.setText((device.getBondState() == BluetoothDevice.BOND_BONDED) ? "Unpair" : "Pair");
holder.pairBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mListener != null) {
mListener.onPairButtonClick(position);
}
}
});
return convertView;
}
static class ViewHolder {
TextView nameTv;
TextView addressTv;
TextView pairBtn;
}
public interface OnPairButtonClickListener {
public abstract void onPairButtonClick(int position);
}
}
in an article i studied about this issue and find out that with this code :
if (ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(context,
new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
1);
i can make the application to support phones with android more than 6 so i can discover all nearby devices and pair with them,
The issue is, i don't know where should i exactly use this code..
i would really appreciate if you could tell me where to use it within the codes i showed here.
or simply tell me how to overcome this problem with any other code you may know.
In your AndroidManifest.xml file add this:
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
Then, instead of calling registerReceiver call this function:
private tryRegisterReceiver() {
if (ContextCompat.checkSelfPermission(thisActivity,
Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Here, permission is not granted
// after calling requestPermissions, the result must be treated in onRequestPermissionResult
ActivityCompat.requestPermissions(thisActivity,
new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
1000); // 100 or other desired code
} else {
// Permission has already been granted
// continue registering your receiver
registerReceiver();
}
}
To treat the result of the permission request
#Override
public void onRequestPermissionsResult(int requestCode,
String[] permissions, int[] grantResults) {
switch (requestCode) {
case 1000: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted
// continue registering your receiver
registerReceiver();
} else {
// permission denied
// show a message or finish your activity
}
return;
}
// other 'case' for other permissions if needed
}
}
I am trying to stream shoutcast URL in my app through media player and it works fine ( no stops after sometime) for API 14 and older (ie. in my friend mobile it works fine who has note 2) but it stops playing after sometime for higher API (ie: my android version is 7 Samsung galaxy S6 edge plus) and it stops for me after sometime.
How can i solve this issue?
below is the code:
ActivityRadio.java
public class ActivityRadio extends BaseActivity {
private String[] navMenuTitles;
private TypedArray navMenuIcons;
Button startButton, stopButton;
static Context context;
boolean isPlaying;
Intent streamService;
SharedPreferences prefs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.radio);
context = getApplicationContext();
navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items); // load
// titles
// from
// strings.xml
navMenuIcons = getResources()
.obtainTypedArray(R.array.nav_drawer_icons);// load icons from
// strings.xml
set(navMenuTitles, navMenuIcons);
AdView adView = (AdView)this.findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder()
//.addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
// .addTestDevice("TEST_DEVICE_ID")
.build();
adView.loadAd(adRequest);
startButton = (Button) findViewById(R.id.startButton);
stopButton = (Button) findViewById(R.id.stopButton);
prefs = PreferenceManager.getDefaultSharedPreferences(context);
getPrefs();
streamService = new Intent(ActivityRadio.this, ServiceRadio.class);
startButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
startService(streamService);
startButton.setEnabled(false);
}
});
stopButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
stopService(streamService);
startButton.setEnabled(true);
}
});
}
public void getPrefs() {
isPlaying = prefs.getBoolean("isPlaying", false);
if (isPlaying) startButton.setEnabled(false);
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK ) {
Intent intent = new Intent(ActivityRadio.this, ActivityMain.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("EXIT", true);
startActivity(intent);
}
return super.onKeyDown(keyCode, event);
}
}
ServiceRadio.java
public class ServiceRadio extends Service implements OnAudioFocusChangeListener {
private static final String TAG = "StreamService";
MediaPlayer mp;
boolean isPlaying;
SharedPreferences prefs;
SharedPreferences.Editor editor;
private AudioManager mAudioManager;
Notification n;
NotificationManager notificationManager;
// Change this int to some number specifically for this app
int notifId = 5315;
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#SuppressWarnings("deprecation")
#Override
public void onCreate() {
super.onCreate();
Log.d(TAG, "onCreate");
// Init the SharedPreferences and Editor
prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
editor = prefs.edit();
// Set up the buffering notification
notificationManager = (NotificationManager) getApplicationContext()
.getSystemService(NOTIFICATION_SERVICE);
Context context = getApplicationContext();
String notifTitle = context.getResources().getString(R.string.app_name);
String notifMessage = context.getResources().getString(R.string.buffering);
n = new Notification();
n.icon = R.drawable.icon;
n.tickerText = "Buffering";
n.when = System.currentTimeMillis();
Intent nIntent = new Intent(context, ActivityRadio.class);
PendingIntent pIntent = PendingIntent.getActivity(context, 0, nIntent, 0);
n.setLatestEventInfo(context, notifTitle, notifMessage, pIntent);
notificationManager.notify(notifId, n);
// It's very important that you put the IP/URL of your ShoutCast stream here
// Otherwise you'll get Webcom Radio
String url = "http://listen.shoutcast.com/fmd";
mp = new MediaPlayer();
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mp.setDataSource(url);
mp.prepare();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
Log.e(TAG, "SecurityException");
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
Log.e(TAG, "IllegalStateException");
} catch (IOException e) {
// TODO Auto-generated catch block
Log.e(TAG, "IOException");
}
mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
mAudioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
}
#Override
public void onAudioFocusChange(int focusChange) {
if(focusChange<=0) {
mp.pause();
} else {
mp.start();
}
}
#SuppressWarnings("deprecation")
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(TAG, "onStart");
mp.start();
// Set the isPlaying preference to true
editor.putBoolean("isPlaying", true);
editor.commit();
Context context = getApplicationContext();
String notifTitle = context.getResources().getString(R.string.app_name);
String notifMessage = context.getResources().getString(R.string.now_playing);
n.icon = R.drawable.icon;
n.tickerText = notifMessage;
n.flags = Notification.FLAG_NO_CLEAR;
n.when = System.currentTimeMillis();
Intent nIntent = new Intent(context, ActivityRadio.class);
PendingIntent pIntent = PendingIntent.getActivity(context, 0, nIntent, 0);
n.setLatestEventInfo(context, notifTitle, notifMessage, pIntent);
// Change 5315 to some nother number
notificationManager.notify(notifId, n);
return Service.START_STICKY; // not supported in SDK
}
#Override
public void onDestroy() {
Log.d(TAG, "onDestroy");
mp.stop();
mp.release();
mp = null;
editor.putBoolean("isPlaying", false);
editor.commit();
notificationManager.cancel(notifId);
mAudioManager.abandonAudioFocus(this);
}
}
use the following line startForeground(notifId, n) instead of this one notificationManager.notify(notifId, n);
When using notifications in a service, the notification also must be persistent.
instead of use startService(streamService);
please use
try {
Intent playbackServiceIntent = new Intent(this, MusicService.class);
startService(playbackServiceIntent);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
startForegroundService(playbackServiceIntent);
}
}catch (Exception e){
e.printStackTrace();
}
I have already been fetched data from instagram api. But i cannot reach that data to use it on my service. I have tried all methods that i know.
**Here is my main object: ** If my followers count is increases or decreases, notify, And check that for every 5 min.(I am still working on it. There are lots of misses yet.)
**Here is my main question: ** Do i really have to create a new parser to fetch data that i already have or what should i build?
If you have any sample or Articles for this case, that would be useful.
I heard about Csv file. Is that can be useful to import ?
PS: I learned java and android studio yet. I am pretty newbie.
public class MyService extends Service {
private InstagramApp mApp;
private HashMap<String, String> userInfoHashmap = new HashMap<String, String>();
#Nullable
#Override
public IBinder onBind(Intent intent) { return null; }
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
mApp = new InstagramApp(this, ApplicationData.CLIENT_ID,
ApplicationData.CLIENT_SECRET, ApplicationData.CALLBACK_URL);
Toast.makeText(this,"Service Started", Toast.LENGTH_LONG).show();
Timer myTimer = new Timer();
myTimer.schedule(new TimerTask() {
#Override
public void run() {
String xx=userInfoHashmap.get(InstagramApp.TAG_FOLLOWED_BY);
getnotification(xx);
}
}, 0, 5000);
return START_STICKY;
}
#Override
public void onDestroy() {
Toast.makeText(this,"Service Stopped", Toast.LENGTH_LONG).show();
}
public void getnotification(String xx){
//String foo=(userInfoHashmap.get(InstagramApp.TAG_FOLLOWED_BY));
// int fo= Integer.parseInt(foo);
// Toast.makeText(this, xx, Toast.LENGTH_LONG).show();
NotificationManager notificationmgr = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
Intent intent = new Intent(this, MainActivity.class);
PendingIntent pintent = PendingIntent.getActivity(this, (int) System.currentTimeMillis(), intent, 0);
//PendingIntent pintent = PendingIntent.getActivities(this,(int)System.currentTimeMillis(),intent, 0);
Notification notif = new Notification.Builder(this)
.setSmallIcon(R.drawable.common_full_open_on_phone)
.setContentTitle("Notifications "+xx)
.setContentText("Followed by="+ userInfoHashmap.get(InstagramApp.TAG_FOLLOWED_BY))
.setContentIntent(pintent)
.build();
notificationmgr.notify(0,notif);
}
/* Uri uri = Uri.parse("http://instagram.com/");
Intent likeIng = new Intent(Intent.ACTION_VIEW, uri);
likeIng.setPackage("com.instagram.android");
try {
startActivity(likeIng);
} catch (ActivityNotFoundException e) {
startActivity(new Intent(Intent.ACTION_VIEW,
Uri.parse("http://instagram.com/xxx")));
}*/
}
Here is my MainActivity
public class MainActivity extends AppCompatActivity implements OnClickListener {
private InstagramApp mApp;
private Button btnConnect;
private Button btnMe, btnOS,btnCS;
private HashMap<String, String> userInfoHashmap = new HashMap<String, String>();
ViewGroup myLayout;
private FirebaseAnalytics mFirebaseAnalytics;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(activity_main);
mFirebaseAnalytics = FirebaseAnalytics.getInstance(this);
myLayout = (ViewGroup)findViewById(R.id.myLayout);
mApp = new InstagramApp(this, ApplicationData.CLIENT_ID,
ApplicationData.CLIENT_SECRET, ApplicationData.CALLBACK_URL);
mApp.setListener(new OAuthAuthenticationListener() {
#Override
public void onSuccess() {
mApp.fetchUserName(handler);
}
#Override
public void onFail(String error) {
Toast.makeText(MainActivity.this, error, Toast.LENGTH_SHORT)
.show();
}
}
);
setWidgetReference();
bindEventHandlers();
if (mApp.hasAccessToken()) {
btnConnect.setText("Disconnect");
mApp.fetchUserName(handler);
}
}
private void setWidgetReference() {
btnConnect = (Button) findViewById(R.id.btnConnect);
btnMe = (Button) findViewById(R.id.btnMy);
btnOS = (Button) findViewById(R.id.btnOS);
btnCS = (Button) findViewById(R.id.btnCS);
}
private void bindEventHandlers() {
btnConnect.setOnClickListener(this);
btnMe.setOnClickListener(this);
btnOS.setOnClickListener(this);
btnCS.setOnClickListener(this);
}
String log="log";
#Override
public void onClick(View v) {
if (v == btnConnect) {
connectOrDisconnectUser();
} else {
String url = "";
if (v == btnMe) {
Log.v(log,"info show");
displayInfoDialogView();
//TODO Usersa string koy. Yeni hesap için.
// url = "https://api.instagram.com/v1/users/self"+ userInfoHashmap.get(InstagramApp.TAG_ID)+ "/?access_token=" + mApp.getTOken(); imageView.setTag(userInfoHashmap.get(InstagramApp.TAG_PROFILE_PICTURE));String imageName = (String) imageView.getTag();String axe=(String) userInfoHashmap.get(InstagramApp.TAG_PROFILE_PICTURE);image.setImageResource(axe);
}
else if (v == btnOS) {
Log.v(log,"Service started");
startService(new Intent(getBaseContext(),MyService.class));
// url = "https://api.instagram.com/v1/users/self/media/recent"+ userInfoHashmap.get(InstagramApp.TAG_ID)+ "/followed-by?access_token="+ mApp.getTOken();
}
//startActivity(new Intent(MainActivity.this, Relationship.class).putExtra("userInfo", url));
else if(v==btnCS){
Log.v(log,"Service closed");
stopService(new Intent(getBaseContext(),MyService.class));
}
}
}
public void goBack(View v){
setContentView(R.layout.activity_main);
}
private void connectOrDisconnectUser() {
if (mApp.hasAccessToken()) {
final AlertDialog.Builder builder = new AlertDialog.Builder(
MainActivity.this);
builder.setMessage("Disconnect from Instagram?")
.setCancelable(false)
.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
mApp.resetAccessToken();
btnConnect.setText("Connect");
}
})
.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
dialog.cancel();
}
});
final AlertDialog alert = builder.create();
alert.show();
} else {
mApp.authorize();
}
}
private Handler handler = new Handler(new Handler.Callback() {
#Override
public boolean handleMessage(Message msg) {
if (msg.what == InstagramApp.WHAT_FINALIZE) {
userInfoHashmap = mApp.getUserInfo();
btnConnect.setText("Disconnect");
} else if (msg.what == InstagramApp.WHAT_ERROR) {
Toast.makeText(MainActivity.this, "Check your network.",
Toast.LENGTH_SHORT).show();
}
return false;
}
});
#Override
protected void onStart() {
super.onStart();
Toast.makeText(this, "Welcome to onStart", Toast.LENGTH_SHORT).show();
}
#Override
protected void onResume() {
super.onResume();
Toast.makeText(this, "Welcome to onResume", Toast.LENGTH_SHORT).show();
}
#Override
protected void onPause() {
super.onPause();
Toast.makeText(this, "It is onPause", Toast.LENGTH_SHORT).show();
}
#Override
protected void onStop() {
super.onStop();
Toast.makeText(this, "Stopped", Toast.LENGTH_SHORT).show();
}
#Override
protected void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Bye Bye :((", Toast.LENGTH_SHORT).show();
}
private void displayInfoDialogView() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this);
alertDialog.setTitle(userInfoHashmap.get(InstagramApp.TAG_USERNAME));
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.activity_follower_list, null);
alertDialog.setView(view);
TextView tvName = (TextView) view.findViewById(R.id.textView3);
TextView tvNoOfFollwers = (TextView) view.findViewById(R.id.textView2);
TextView tvNoOfFollowing = (TextView) view.findViewById(R.id.textView4);
//new ImageLoader(MainActivity.this).DisplayImage(userInfoHashmap.get(InstagramApp.TAG_PROFILE_PICTURE), ivProfile);
tvName.setText(userInfoHashmap.get(InstagramApp.TAG_USERNAME));
tvNoOfFollowing.setText(userInfoHashmap.get(InstagramApp.TAG_FOLLOWS));
tvNoOfFollwers.setText(userInfoHashmap.get(InstagramApp.TAG_FOLLOWED_BY));
alertDialog.create().show();
}
public void getnotification(){
String xx = userInfoHashmap.get(InstagramApp.TAG_FOLLOWED_BY);
/* Toast.makeText(this, xx, Toast.LENGTH_LONG)
.show();
*/
if (xx!=xx ) {
NotificationManager notificationmgr = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
// Intent intent = new Intent(this, resultpage.class);
// PendingIntent pintent = PendingIntent.getActivity(this, (int) System.currentTimeMillis(), intent, 0);
// PendingIntent pintent = PendingIntent.getActivities(this,(int)System.currentTimeMillis(),intent, 0);
Notification notif = new Notification.Builder(this)
.setSmallIcon(R.drawable.common_google_signin_btn_text_dark_pressed)
.setContentTitle("Bu bir Bildirimdir!")
.setContentText("Bu bildirimin içeriğidir.")
//.setContentIntent(pintent)
.build();
notificationmgr.notify(0,notif);
}
}
}
The only solution that i found is the adding parser to your service to reach data from api. None of the the method can access to reach data from service to activity.
I added this class to reach api data on service.
public void lilParser() throws IOException, JSONException{
URL url = new URL(API_URL + "/users/" + mSession.getId()
+ "/?access_token=" + mAccessToken);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoInput(true);
urlConnection.connect();
String response = Utils.streamToString(urlConnection
.getInputStream());
System.out.println(response);
JSONObject jsonObj = (JSONObject) new JSONTokener(response).nextValue();
JSONObject data_obj = jsonObj.getJSONObject("data");
JSONObject counts_obj = data_obj.getJSONObject("counts");
String name = jsonObj.getJSONObject("data").getString("full_name");
String bio =jsonObj.getJSONObject("data").getString("bio");
String counts=jsonObj.getJSONObject("data").getString("counts");
userInfoHashmap.put(TAG_FOLLOWED_BY,counts_obj.getString(TAG_FOLLOWED_BY));
Log.i(TAG,"followedby=>[" + counts + "]");
}
And, Here is my onCreate. You can check The data if it is changed or not.
#Override
public void onCreate() {
Toast.makeText(this,"Service Started", Toast.LENGTH_LONG).show();
myTimer = new Timer();
myTimer.schedule(new TimerTask() {
#Override
public void run() {
String fo = userInfoHashmap.get(TAG_FOLLOWED_BY);
try {
lilParser();
}
catch (IOException e) {e.printStackTrace();}
catch (JSONException e) {e.printStackTrace();}
if(new String(userInfoHashmap.get(TAG_FOLLOWED_BY)).equals(fo)==true){}
else {
getnotification();
}
}
}, 0, 30000);
}
PS: I published my code, that may help someone else. I am still newbie.
This is my GcmIntentService class by which i am sending the message. The problem is when i click on the push notification message it opens the main activity.but i want to open the particular fragment.I knew for that some changes would be in sendNotification()method. Can anyone tell me how can i open the particular fragment on the click of the push notification ?
public class GcmIntentService extends IntentService {
public static final int NOTIFICATION_ID = 1;
private NotificationManager mNotificationManager;
private final static String TAG = "GcmIntentService";
public GcmIntentService() {
super("GcmIntentService");
}
#Override
protected void onHandleIntent(Intent intent) {
Bundle extras = intent.getExtras();
GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
String messageType = gcm.getMessageType(intent);
if (!extras.isEmpty()) {
if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR
.equals(messageType)) {
sendNotification("Send error: " + extras.toString());
} else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED
.equals(messageType)) {
sendNotification("Deleted messages on server: " + extras.toString());
} else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE
.equals(messageType)) {
for (int i = 0; i < 5; i++) {
Log.d(TAG, " Working... " + (i + 1) + "/5 # "
+ SystemClock.elapsedRealtime());
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
sendNotification(extras.getString("message"));
}
} WakefulBroadcastReceiver.
GcmBroadcastReceiver.completeWakefulIntent(intent);
}
private void sendNotification(String msg) {
mNotificationManager = (NotificationManager) this
.getSystemService(Context.NOTIFICATION_SERVICE);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), 0);
NotificationCompat.Builder mBuilder = (NotificationCompat.Builder) new NotificationCompat.Builder(this)
.setSmallIcon(getNotificationIcon())
.setContentTitle("Telepoh")
.setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
.setContentText(msg)
.setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE);
mBuilder.setContentIntent(contentIntent);
mBuilder.getNotification().flags |= Notification.FLAG_AUTO_CANCEL;
mBuilder.setAutoCancel(true);
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
}
private int getNotificationIcon() {
boolean useWhiteIcon = (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP);
return useWhiteIcon ? R.drawable.gcm : R.drawable.push_icon;
}
}
This is the fragment which i want to open on the click of the push notification message:-
public class NotificationActivity extends Fragment {
ProgressDialog pd;
private SharedPreferencesUtilities sharedPreferencesUtilities;
private GeneralUtilities generalUtilities;
private View rootView;
private ListView listView;
private TextView txtKm;
private TextView emptyView;
int progressValue=0;
int progressValue2;
public NotificationActivity notilist = null;
HttpResponse response;
public ArrayList<ListViewItem> notiarray = new ArrayList<ListViewItem>();
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if (rootView == null) {
rootView = inflater.inflate(R.layout.notification_screen, container, false);
getActivity().setTitle("Notifications");
generalUtilities = new GeneralUtilities(getActivity());
sharedPreferencesUtilities = new SharedPreferencesUtilities(getActivity());
notilist = this;
new GetNotificationData().execute();
}
return rootView;
}
public class GetNotificationData extends AsyncTask<String , String , String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(getActivity());
pd.setCancelable(true);
pd.setMessage("Loading...");
pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pd.show();
}
#Override
protected String doInBackground(String... params) {
notificationlistData();
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
pd.dismiss();
if (generalUtilities.isConnected()) {
HttpEntity entity = response.getEntity();
String json = null;
try {
json = EntityUtils.toString(entity);
} catch (IOException e) {
e.printStackTrace();
}
try {
final JSONObject jObject = new JSONObject(json);
if (jObject.getString("ReplyCode").equals("1")) {
JSONArray jsonUserObject = jObject.getJSONArray("data");
for (int i = 0; i < jsonUserObject.length(); i++) {
notiarray.add(new ListViewItem(jsonUserObject.getJSONObject(i).getString("OtherUserName"),
jsonUserObject.getJSONObject(i).getString("UserProfilePic"), jsonUserObject.getJSONObject(i).getString("Status"),
jsonUserObject.getJSONObject(i).getString("ID"),jsonUserObject.getJSONObject(i).getString("EventsID"),
jsonUserObject.getJSONObject(i).getString("OtherUserID")));
}
Resources res =getResources();
listView = (ListView) rootView.findViewById(R.id.notification_list);
emptyView = (TextView) rootView.findViewById(R.id.empty_view);
if (notiarray.isEmpty()) {
listView.setVisibility(View.GONE);
emptyView.setVisibility(View.VISIBLE);
}
else {
listView.setVisibility(View.VISIBLE);
emptyView.setVisibility(View.GONE);
NotificationAdapter nAdapter = new NotificationAdapter(notilist, notiarray, res);
listView.setAdapter(nAdapter);
}
} else {
generalUtilities.showAlertDialog("Request Cancelled", new JSONObject(json).getString("Message"), "OK");
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
generalUtilities.showAlertDialog("Error", getResources().getString(R.string.internet_error), "OK");
}
}
}
public void notificationlistData() {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(getResources().getString(R.string.api_end_point) + "ShowNotification/NotificationData");
httppost.setHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded;charset=UTF-8");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("ID", String.valueOf(sharedPreferencesUtilities.getUserId())));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.main_distance, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_distance:
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
View dialogView = inflater.inflate(R.layout.setdistance_popup, null);
dialogBuilder.setView(dialogView);
final AlertDialog alertDialog = dialogBuilder.create();
alertDialog.show();
TextView txtTitle = (TextView) dialogView.findViewById(R.id.textView58);
txtKm = (TextView) dialogView.findViewById(R.id.textView500);
TextView txthn = (TextView) dialogView.findViewById(R.id.textView59);
TextView txtDiscription = (TextView) dialogView.findViewById(R.id.textView63);
LinearLayout btnSet = (LinearLayout) dialogView.findViewById(R.id.buttonSet);
LinearLayout btnCancel = (LinearLayout) dialogView.findViewById(R.id.buttonCancel);
txthn.setText(10+sharedPreferencesUtilities.getRadiodistance());
SeekBar popupSeek = (SeekBar) dialogView.findViewById(R.id.seekBar2);
if(sharedPreferencesUtilities.getProfiledistance()=="")
{
popupSeek.setProgress(0);
txtKm.setText("500 Meter");
}
else
{
Integer checkCount = Integer.parseInt(sharedPreferencesUtilities.getProfiledistance());
if(checkCount==0)
{
popupSeek.setProgress(0);
txtKm.setText("500 Meter");
}
else
{
popupSeek.setProgress(Integer.parseInt(sharedPreferencesUtilities.getProfiledistance()));
txtKm.setText(sharedPreferencesUtilities.getProfiledistance() + sharedPreferencesUtilities.getRadiodistance());
}
}
popupSeek.setMax(10);
popupSeek.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
// progress = ((int)Math.round(progress/0.5));
progressValue2 = progressValue+progress;
if(progress==0)
{
txtKm.setText("500 Meter");
}
else {
txtKm.setText(Integer.toString(progressValue2) + sharedPreferencesUtilities.getRadiodistance());
}
}
});
btnSet.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sharedPreferencesUtilities.setProfiledistance(String.valueOf(progressValue2));
alertDialog.dismiss();
}
});
btnCancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
alertDialog.dismiss();
}
});
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
Manage some flag and pass information from notification to MainActivity via Intent.
use switch case or if/else in your MainActivity, if you are receiving perticular flag/data, load desired fragment.
Intent passIntent = new Intent(this, MainActivity.class);
passIntent.putExtra("flag","some value");
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, passIntent, 0);
in your MainActivity.java
if(getIntent().hasExtra("flag")){
if(getIntent.getStringExtra("flag").equalsIgnorCase("some value"))
{
//write code to load your fragment.
}
}
I have two implementations of AlarmManager which are supposed to start two services - LMW and BWM - for some reason BWM starts each time and LMW does not. I've looked the source code over many times and I'm really not sure why this could be happening.
P.S.
adb shell dumpsys alarm shows a reference to BWM but no reference to LWM
Any input is greatly appreciated!
ALARMMANAGER SOURCE:
public class Rules extends Activity {
private String password;
private PendingIntent mPendingIntent;
String TIMELIMIT = "10";
TextView textSsid, textSpeed, textRssi, Time;
private static final int NOTIFY_ME_ID = 1337;
private int count = 0;
private NotificationManager notifyMgr = null;
public Handler mHandler = new Handler();
public long mStartRX = 0;
public long mStartTX = 0;
public long txBytes;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.rules);
String NDEF_PREF = "prefs";
SharedPreferences prefs = getSharedPreferences(NDEF_PREF,
Context.MODE_PRIVATE);
String name = prefs.getString("name", "");
String code = prefs.getString("corename", "");
String time = prefs.getString("time", "");
String ssid = prefs.getString("restricted", "");
Time = (TextView) findViewById(R.id.Time);
Time.setText(time);
textSsid = (TextView) findViewById(R.id.Ssid);
textSpeed = (TextView) findViewById(R.id.Speed);
textRssi = (TextView) findViewById(R.id.Rssi);
Time = (TextView) findViewById(R.id.Time);
Long.toString(mStartTX);
Long.toString(mStartRX);
Long.toString(txBytes);
mStartRX = TrafficStats.getTotalRxBytes();
mStartTX = TrafficStats.getTotalTxBytes();
if (mStartRX == TrafficStats.UNSUPPORTED
|| mStartTX == TrafficStats.UNSUPPORTED) {
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Uh Oh!");
alert.setMessage("Your device does not support traffic stat monitoring.");
alert.show();
} else {
mHandler.postDelayed(mRunnable, 1000);
}
}
private final Runnable mRunnable = new Runnable() {
public void run() {
TextView RX = (TextView) findViewById(R.id.RX);
TextView TX = (TextView) findViewById(R.id.TX);
long rxBytes = TrafficStats.getTotalRxBytes() - mStartRX;
RX.setText(Long.toString(rxBytes));
long txBytes = TrafficStats.getTotalTxBytes() - mStartTX;
TX.setText(Long.toString(txBytes));
mHandler.postDelayed(mRunnable, 1000);
final Chronometer myChronometer = (Chronometer) findViewById(R.id.chronometer);
myChronometer.start();
DisplayWifiState();
this.registerReceiver(this.myWifiReceiver, new IntentFilter(
ConnectivityManager.CONNECTIVITY_ACTION));
}
private void registerReceiver(BroadcastReceiver myWifiReceiver2,
IntentFilter intentFilter) {
// TODO Auto-generated method stub
}
private BroadcastReceiver myWifiReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context arg0, Intent arg1) {
// TODO Auto-generated method stub
NetworkInfo networkInfo = (NetworkInfo) arg1
.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
DisplayWifiState();
}
}
};
public Date getTimeFromTimeString(String time) {
String[] splitStrings = time.split(":");
Date timeDate = new Date();
timeDate.setHours(Integer.parseInt(splitStrings[0]));
timeDate.setMinutes(Integer.parseInt(splitStrings[1]));
return timeDate;
}
// Long.parseLong(time)
public void DisplayWifiState() {
ConnectivityManager myConnManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo myNetworkInfo = myConnManager
.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
WifiManager myWifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiInfo myWifiInfo = myWifiManager.getConnectionInfo();
if (myNetworkInfo.isConnected()) {
textSsid.setText(myWifiInfo.getSSID());
textSpeed.setText(String.valueOf(myWifiInfo.getLinkSpeed())
+ " " + WifiInfo.LINK_SPEED_UNITS);
textRssi.setText(String.valueOf(myWifiInfo.getRssi()));
} else {
textSsid.setText("---");
textSpeed.setText("---");
textRssi.setText("---");
}
;
// Start service using AlarmManager
Calendar cal = Calendar.getInstance();
cal.add(Calendar.SECOND, 10);
Intent intent = new Intent(Rules.this, LMW.class);
PendingIntent pintent = PendingIntent.getService(Rules.this, 0,
intent, 0);
AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
7 * 1000, pintent);
String NDEF_PREF = "prefs";
SharedPreferences prefs = getSharedPreferences(NDEF_PREF,
Context.MODE_PRIVATE);
String name = prefs.getString("name", "");
String code = prefs.getString("corename", "");
String time = prefs.getString("time", "");
String ssid = prefs.getString("restricted", "");
// Start 2nd service using AlarmManager
// Calendar cal = Calendar.getInstance();
// cal.add(Calendar.SECOND, 10);
// Intent intent2 = new Intent(Rules.this, KillTimer.class);
// PendingIntent pintent2 = PendingIntent.getActivity(Rules.this, 0,
// intent2,
// 0);
// AlarmManager alarm2 = (AlarmManager)
// getSystemService(Context.ALARM_SERVICE);
// alarm2.setRepeating(AlarmManager.RTC_WAKEUP,
// cal.getTimeInMillis(),
// time != null ? 1000 : 0, pintent2);
// Date futureDate = new Date(new Date().getTime() + 86400000);
// futureDate.setHours(8);
// futureDate.setMinutes(0);
// futureDate.setSeconds(0);
// Start 3rd service using AlarmManager
Intent intent3 = new Intent(Rules.this, BWM.class);
PendingIntent pintent3 = PendingIntent.getActivity(Rules.this, 0,
intent3, 0);
AlarmManager alarm3 = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarm3.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
7 * 1000, pintent3);
// click listener for the button to start service
Button btnStart = (Button) findViewById(R.id.button1);
btnStart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startService(new Intent(getBaseContext(), LMW.class));
startService(new Intent(getBaseContext(), BWM.class));
Intent startMain = new Intent(Intent.ACTION_MAIN);
startMain.addCategory(Intent.CATEGORY_HOME);
startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(startMain);
}
});
// click listener for the button to stop service
Button btnStop = (Button) findViewById(R.id.button2);
btnStop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
stopService(new Intent(getBaseContext(), LMW.class));
Intent startMain = new Intent(Intent.ACTION_MAIN);
startMain.addCategory(Intent.CATEGORY_HOME);
startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(startMain);
}
});
}
};
}
LMW SOURCE:
public class LMW extends Service {
String Watchdog = "Watchdog";
String Dirty1 = "playboy";
String Dirty2 = "penthouse";
String Dirty3 = "pornhub";
String Dirty4 = "thepiratebay";
String Dirty5 = "vimeo";
String Dirty6 = "wired";
String Dirty7 = "limewire";
String Dirty8 = "whitehouse";
String Dirty9 = "hackaday";
String Dirty10 = "slashdot";
Long mStartRX = TrafficStats.getTotalRxBytes();
Long mStartTX = TrafficStats.getTotalTxBytes();
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(getApplicationContext(), "Watchdog Running!",
Toast.LENGTH_SHORT).show();
Parse.initialize(this, "7gjqmUcoqu1IZPJSSxXLdE4L8efAugCXA7snLSH6",
"5NckF83MUBumQ8L8zL7Akc4p07beMRnmvgCfhZdH");
ParseUser.enableAutomaticUser();
ParseACL defaultACL = new ParseACL();
// If you would like all objects to be private by default, remove this
// line.
defaultACL.setPublicReadAccess(true);
ParseACL.setDefaultACL(defaultACL, true);
Long.toString(mStartTX);
Long.toString(mStartRX);
ParseObject testObject = new ParseObject("TestObject");
testObject.put("DataO", String.valueOf(mStartTX));
testObject.put("DataI", String.valueOf(mStartRX));
testObject.saveInBackground();
String[] projection = new String[] { Browser.BookmarkColumns.TITLE,
Browser.BookmarkColumns.URL };
Cursor cursor = getContentResolver().query(
android.provider.Browser.BOOKMARKS_URI, projection, null, null,
null);
String urls = "";
if (cursor.moveToFirst()) {
String url1 = null;
String url2 = null;
do {
String url = cursor.getString(cursor
.getColumnIndex(Browser.BookmarkColumns.URL));
// Log.i(Watchdog, url);
if (url.toLowerCase().contains(Dirty1)
|| url.toLowerCase().contains(Dirty2)
|| url.toLowerCase().contains(Dirty3)
|| url.toLowerCase().contains(Dirty4)
|| url.toLowerCase().contains(Dirty5)
|| url.toLowerCase().contains(Dirty6)
|| url.toLowerCase().contains(Dirty7)
|| url.toLowerCase().contains(Dirty8)
|| url.toLowerCase().contains(Dirty9)
|| url.toLowerCase().contains(Dirty10)) {
Intent intent2 = new Intent(LMW.this, Warning.class);
intent2.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent2);
break;
}
} while (cursor.moveToNext());
}
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service Stopped", Toast.LENGTH_LONG).show();
}
#Override
public void onCreate() {
super.onCreate();
}
}