Does Service needs another parser? - java

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.

Related

Scanning for bluetooth devices programmatically don't find anything in android 6+

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
}
}

splash screen getting value from the service

I have splash screen which has count down time. I am assigning time value manually in my example time = 10000.
1)How can I assign value which I am getting from the service to the time variable.
2) How can I compare both the time and then assign the service time to the splash screen activity.
Activity
TextView text1, text2, text3;
// int time= 3600000*8;
int time = 10000;
public int Main_time ;
private UsbService usbService;
private EditText editText;
private MyHandler mHandler;
StringBuilder stringBuilder = new StringBuilder();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash_screen);
mHandler = new MyHandler(splash_screen.this);
splashScreenUseAsyncTask();
int mUIFlag = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_LOW_PROFILE
| View.SYSTEM_UI_FLAG_FULLSCREEN
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;
getWindow().getDecorView().setSystemUiVisibility(mUIFlag);
text1 = (TextView) findViewById(R.id.tv_hour);
text2 = (TextView) findViewById(R.id.tv_minute);
text3 = (TextView) findViewById(R.id.tv_second);
}
private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
switch (intent.getAction()) {
case UsbService.ACTION_USB_PERMISSION_GRANTED: // USB PERMISSION GRANTED
Toast.makeText(context, "USB Ready", Toast.LENGTH_SHORT).show();
break;
case UsbService.ACTION_USB_PERMISSION_NOT_GRANTED: // USB PERMISSION NOT GRANTED
Toast.makeText(context, "USB Permission not granted", Toast.LENGTH_SHORT).show();
break;
case UsbService.ACTION_NO_USB: // NO USB CONNECTED
Toast.makeText(context, "No USB connected", Toast.LENGTH_SHORT).show();
break;
case UsbService.ACTION_USB_DISCONNECTED: // USB DISCONNECTED
Toast.makeText(context, "USB disconnected", Toast.LENGTH_SHORT).show();
break;
case UsbService.ACTION_USB_NOT_SUPPORTED: // USB NOT SUPPORTED
Toast.makeText(context, "USB device not supported", Toast.LENGTH_SHORT).show();
break;
}
}
};
private final ServiceConnection usbConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName arg0, IBinder arg1) {
usbService = ((UsbService.UsbBinder) arg1).getService();
usbService.setHandler(mHandler);
//usbService.sendATGetESN();
//usbService.sendATGetSTART();
//usbService.sendATGetPC();
//usbService.sendATGetSTOP();
usbService.sendATGetACC();
}
#Override
public void onServiceDisconnected(ComponentName arg0) {
usbService = null;
}
};
#Override
public void onResume() {
super.onResume();
setFilters(); // Start listening notifications from UsbService
startService(UsbService.class, usbConnection, null); // Start UsbService(if it was not started before) and Bind it
}
#Override
public void onPause() {
try {
unregisterReceiver(mUsbReceiver);
unbindService(usbConnection);
} catch (IllegalArgumentException ex) {
}
super.onPause();
}
#Override
public void onDestroy() {
try{
if(mUsbReceiver!=null)
unregisterReceiver(mUsbReceiver);
}catch(Exception e){}
super.onDestroy();
}
private void startService(Class<?> service, ServiceConnection serviceConnection, Bundle extras) {
Intent serviceIntent = new Intent(this, splash_screen.class);
this.startService(serviceIntent);
startService(serviceIntent);
if (!UsbService.SERVICE_CONNECTED) {
Intent startService = new Intent(this, splash_screen.class);
if (extras != null && !extras.isEmpty()) {
Set<String> keys = extras.keySet();
for (String key : keys) {
String extra = extras.getString(key);
startService.putExtra(key, extra);
}
}
startService(startService);
}
Intent bindingIntent = new Intent(this, service);
bindService(bindingIntent, serviceConnection, Context.BIND_AUTO_CREATE);
}
private void setFilters() {
IntentFilter filter = new IntentFilter();
filter.addAction(UsbService.ACTION_USB_PERMISSION_GRANTED);
filter.addAction(UsbService.ACTION_NO_USB);
filter.addAction(UsbService.ACTION_USB_DISCONNECTED);
filter.addAction(UsbService.ACTION_USB_NOT_SUPPORTED);
filter.addAction(UsbService.ACTION_USB_PERMISSION_NOT_GRANTED);
registerReceiver(mUsbReceiver, filter);
}
public class MyHandler extends Handler {
private final WeakReference<splash_screen> mActivity;
public MyHandler(splash_screen activity) {
mActivity = new WeakReference<>(activity);
}
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case UsbService.MESSAGE_FROM_SERIAL_PORT:
String data = (String) msg.obj;
StringBuilder main= mActivity.get().stringBuilder.append(data);
Main_time = Integer.parseInt(main.toString());
Log.d("REPLY", "Processing Accumulator List Command22"+Main_time);
break;
}
}
}
private void splashScreenUseAsyncTask() {
// Create a AsyncTask object.
final RetrieveDateTask retrieveDateTask = new RetrieveDateTask();
retrieveDateTask.execute("", "", "");
// Get splash image view object.
final ImageView splashImageView = (ImageView) findViewById(R.id.logo_id);
//for 5 Hours
CountDownTimer countDownTimer = new CountDownTimer(time, 1000) {
#Override
public void onTick(long l) {
//long Days = l / (24 * 60 * 60 * 1000);
long Hours = l / (60 * 60 * 1000) % 24;
long Minutes = l / (60 * 1000) % 60;
long Seconds = l / 1000 % 60;
// tv_days.setText(String.format("%02d", Days));
text1.setText(String.format("%02d", Hours));
text2.setText(String.format("%02d", Minutes));
text3.setText(String.format("%02d", Seconds));
AlphaAnimation anim = new AlphaAnimation(1.0f, 0.0f);
anim.setDuration(500);
anim.setRepeatCount(anim.INFINITE);
anim.setRepeatMode(Animation.REVERSE);
splashImageView.startAnimation(anim);
}
#Override
public void onFinish() {
// When count down complete, set the image to invisible.
//imageAplha = 0;
//splashImageView.setAlpha(imageAplha);
// If AsyncTask is not complete, restart the counter to count again.
if (!retrieveDateTask.isAsyncTaskComplete()) {
this.start();
}
}
};
// Start the count down timer.
countDownTimer.start();
}
// This is the async task class that get data from network.
private class RetrieveDateTask extends AsyncTask<String, String, String> {
// Indicate whether AsyncTask complete or not.
private boolean asyncTaskComplete = false;
public boolean isAsyncTaskComplete() {
return asyncTaskComplete;
}
public void setAsyncTaskComplete(boolean asyncTaskComplete) {
this.asyncTaskComplete = asyncTaskComplete;
}
// This method will be called before AsyncTask run.
#Override
protected void onPreExecute() {
this.asyncTaskComplete = false;
}
// This method will be called when AsyncTask run.
#Override
protected String doInBackground(String... strings) {
try {
// Simulate a network operation which will last for 10 seconds.
Thread currTread = Thread.currentThread();
currTread.sleep(time);
} catch (Exception ex) {
ex.printStackTrace();
} finally {
return null;
}
}
// This method will be called after AsyncTask run.
#Override
protected void onPostExecute(String s) {
// Start SplashScreenMainActivity.
Intent mainIntent = new Intent(splash_screen.this,
MainActivity.class);
splash_screen.this.startActivity(mainIntent);
// Close SplashScreenActivity.
splash_screen.this.finish();
this.asyncTaskComplete = true;
}
}
Service
long sec = Integer.parseInt(value9);
long result = TimeUnit.SECONDS.toMillis(sec);
Log.d("REPLY","Milli"+ result);
String s = String.valueOf(result);
if (mHandler != null) {
mHandler.obtainMessage(MESSAGE_FROM_SERIAL_PORT, s).sendToTarget();
}
new MyTask().execute();
private class MyTask extends AsyncTask<Void,Void,Long>{
#Override
protected Long doInBackground(Void... voids) {
//after downloading or after getting time from service that time for example 3000 we received
return 3000l;
}
#Override
protected void onPostExecute(Long aLong) {
super.onPostExecute(aLong);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
startActivity(new Intent(SplashScreen.this,MainActivity.class));
}
},timeinMs);
}
}
public class splash_screen extends AppCompatActivity {
TextView text1, text2, text3,display;
// int time= 3600000*8;
public String data;
private UsbService usbService;
private EditText editText;
private MyHandler mHandler;
public StringBuilder stringBuilder = new StringBuilder();
long time = 60000;
private long result ;
private long result2 ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash_screen);
mHandler = new MyHandler(splash_screen.this);
int mUIFlag = View.SYSTEM_UI_FLAG_LOW_PROFILE
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;
getWindow().getDecorView().setSystemUiVisibility(mUIFlag);
text1 = (TextView) findViewById(R.id.tv_hour);
text2 = (TextView) findViewById(R.id.tv_minute);
text3 = (TextView) findViewById(R.id.tv_second);
}
private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
switch (intent.getAction()) {
case UsbService.ACTION_USB_PERMISSION_GRANTED: // USB PERMISSION GRANTED
Toast.makeText(context, "USB Ready", Toast.LENGTH_SHORT).show();
break;
case UsbService.ACTION_USB_PERMISSION_NOT_GRANTED: // USB PERMISSION NOT GRANTED
Toast.makeText(context, "USB Permission not granted", Toast.LENGTH_SHORT).show();
break;
case UsbService.ACTION_NO_USB: // NO USB CONNECTED
Toast.makeText(context, "No USB connected", Toast.LENGTH_SHORT).show();
break;
case UsbService.ACTION_USB_DISCONNECTED: // USB DISCONNECTED
Toast.makeText(context, "USB disconnected", Toast.LENGTH_SHORT).show();
break;
case UsbService.ACTION_USB_NOT_SUPPORTED: // USB NOT SUPPORTED
Toast.makeText(context, "USB device not supported", Toast.LENGTH_SHORT).show();
break;
}
}
};
private final ServiceConnection usbConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName arg0, IBinder arg1) {
usbService = ((UsbService.UsbBinder) arg1).getService();
usbService.setHandler(mHandler);
usbService.sendATGetACC();
}
#Override
public void onServiceDisconnected(ComponentName arg0) {
usbService = null;
}
};
#Override
public void onResume() {
super.onResume();
setFilters(); // Start listening notifications from UsbService
startService(UsbService.class, usbConnection, null); // Start UsbService(if it was not started before) and Bind it
}
#Override
public void onPause() {
try {
unregisterReceiver(mUsbReceiver);
unbindService(usbConnection);
} catch (IllegalArgumentException ex) {
}
super.onPause();
}
#Override
public void onDestroy() {
try{
if(mUsbReceiver!=null)
unregisterReceiver(mUsbReceiver);
}catch(Exception e){}
super.onDestroy();
}
private void startService(Class<?> service, ServiceConnection serviceConnection, Bundle extras) {
Intent serviceIntent = new Intent(this, splash_screen.class);
this.startService(serviceIntent);
startService(serviceIntent);
if (!UsbService.SERVICE_CONNECTED) {
Intent startService = new Intent(this, splash_screen.class);
if (extras != null && !extras.isEmpty()) {
Set<String> keys = extras.keySet();
for (String key : keys) {
String extra = extras.getString(key);
startService.putExtra(key, extra);
}
}
startService(startService);
}
Intent bindingIntent = new Intent(this, service);
bindService(bindingIntent, serviceConnection, Context.BIND_AUTO_CREATE);
}
private void setFilters() {
IntentFilter filter = new IntentFilter();
filter.addAction(UsbService.ACTION_USB_PERMISSION_GRANTED);
filter.addAction(UsbService.ACTION_NO_USB);
filter.addAction(UsbService.ACTION_USB_DISCONNECTED);
filter.addAction(UsbService.ACTION_USB_NOT_SUPPORTED);
filter.addAction(UsbService.ACTION_USB_PERMISSION_NOT_GRANTED);
registerReceiver(mUsbReceiver, filter);
}
public class MyHandler extends Handler {
private final WeakReference<splash_screen> mActivity;
public MyHandler(splash_screen activity) {
mActivity = new WeakReference<>(activity);
}
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case UsbService.MESSAGE_FROM_SERIAL_PORT:
String data = (String) msg.obj;
mActivity.get().time(data);
break;
}
}
}
public void time(String data) {
long sec = Integer.parseInt(data);
result = TimeUnit.SECONDS.toMillis(sec);
Log.d("REPLY", "Result value"+result);
result2 = time - result;
Log.d("REPLY", "Result2 value"+result2);
Log.d("REPLY", "Time value"+time);
if(result>=time) {
//usbService.sendATGetSTOP();
Intent mainIntent = new Intent(splash_screen.this,
MainActivity.class);
splash_screen.this.startActivity(mainIntent);
// Close SplashScreenActivity.
splash_screen.this.finish();
}
else{
if (result >= time) {
// usbService.sendATGetSTOP();
Intent mainIntent = new Intent(splash_screen.this,
MainActivity.class);
splash_screen.this.startActivity(mainIntent);
// Close SplashScreenActivity.
splash_screen.this.finish();
} else {
// Log.d("REPLY", "result2 value " + result2);
splashScreenUseAsyncTask();
} }
}
private void splashScreenUseAsyncTask() {
// Create a AsyncTask object.
final RetrieveDateTask retrieveDateTask = new RetrieveDateTask();
retrieveDateTask.execute("", "", "");
// Get splash image view object.
final ImageView splashImageView = (ImageView) findViewById(R.id.logo_id);
//for 5 Hours
CountDownTimer countDownTimer = new CountDownTimer(result2, 1000) {
#SuppressLint("DefaultLocale")
#Override
public void onTick(long l) {
long Hours = l / (60 * 60 * 1000) % 24;
long Minutes = l / (60 * 1000) % 60;
long Seconds = l / 1000 % 60;
// tv_days.setText(String.format("%02d", Days));
text1.setText(String.format("%02d", Hours));
text2.setText(String.format("%02d", Minutes));
text3.setText(String.format("%02d", Seconds));
AlphaAnimation anim = new AlphaAnimation(1.0f, 0.0f);
anim.setDuration(500);
anim.setRepeatCount(anim.INFINITE);
anim.setRepeatMode(Animation.REVERSE);
splashImageView.startAnimation(anim);
}
#Override
public void onFinish() {
if (!retrieveDateTask.isAsyncTaskComplete()) {
this.start();
}
}
};
// Start the count down timer.
countDownTimer.start();
}
// This is the async task class that get data from network.
#SuppressLint("StaticFieldLeak")
private class RetrieveDateTask extends AsyncTask<String, String, String> {
// Indicate whether AsyncTask complete or not.
private boolean asyncTaskComplete = false;
public boolean isAsyncTaskComplete() {
return asyncTaskComplete;
}
public void setAsyncTaskComplete(boolean asyncTaskComplete) {
this.asyncTaskComplete = asyncTaskComplete;
}
// This method will be called before AsyncTask run.
#Override
protected void onPreExecute() {
this.asyncTaskComplete = false;
}
// This method will be called when AsyncTask run.
#Override
protected String doInBackground(String... strings) {
try {
// Simulate a network operation which will last for 10 seconds.
Thread currTread = Thread.currentThread();
currTread.sleep(result2);
} catch (Exception ex) {
ex.printStackTrace();
} finally {
return null;
}
}
// This method will be called after AsyncTask run.
#Override
protected void onPostExecute(String s) {
//usbService.sendATGetSTOP();
// Start SplashScreenMainActivity.
Intent mainIntent = new Intent(splash_screen.this,
MainActivity.class);
splash_screen.this.startActivity(mainIntent);
// Close SplashScreenActivity.
splash_screen.this.finish();
this.asyncTaskComplete = true;
usbService.sendATGetACC();
}
}
}

If RecyclerView scrolls, then item id changes. How to resolve this?

This is my PDFListAdapter class method. I have downloaded file locally and save on Sqlite database. But if I scroll my RecyclerView, then I am having different item id. If not scroll RecyclerView then item id is perfect.
The problem is when I scroll down the RecyclerView the item id changes. That is, I can fit one item on the screen at once. When I scroll to the second item, it saves different file and opens different.
public class PDFListAdapter extends RecyclerView.Adapter<PDFListAdapter.MyViewHolder> {
private ArrayList<NotesResponseInfo> pdfModelClasses;
Context context;
static NotesResponseInfo pdfList;
String final_nav_opt_name;
ProgressDialog progressDialog;
String TAG = "PDFListAdapter";
private NotificationManager mNotifyManager;
private NotificationCompat.Builder mBuilder;
int id = 1;
DatabaseNotes databaseNotes;
MyViewHolder holder;
Downloader downloader;
int deepak =0 ;
public PDFListAdapter(Context context, ArrayList<NotesResponseInfo> pdfModelClasses, String final_nav_opt_name) {
this.context = context;
this.pdfModelClasses = pdfModelClasses;
this.final_nav_opt_name = final_nav_opt_name;
databaseNotes = new DatabaseNotes(context);
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView txtBookName, txtBookTitle, txtBookBookDateOFIssue, txtBookCategory, txtDownload;
LinearLayout layout_open_pdf, layout_download_note_option;
ImageView imgDownloadNote, imgCancelDownloadNote;
ProgressBar progress_download_note;
public MyViewHolder(View view) {
super(view);
txtBookName = (TextView) view.findViewById(R.id.txtBookName);
txtBookTitle = (TextView) view.findViewById(R.id.txtBookTitle);
txtBookBookDateOFIssue = (TextView) view.findViewById(R.id.txtBookBookDateOFIssue);
txtBookCategory = (TextView) view.findViewById(R.id.txtBookCategory);
txtDownload = view.findViewById(R.id.txtDownload);
layout_open_pdf = (LinearLayout) view.findViewById(R.id.layout_open_pdf);
layout_download_note_option = (LinearLayout) view.findViewById(R.id.layout_download_note_option);
imgDownloadNote = (ImageView) view.findViewById(R.id.imgDownloadNote);
progress_download_note = (ProgressBar) view.findViewById(R.id.progress_download_note);
imgCancelDownloadNote = (ImageView) view.findViewById(R.id.imgCancelDownloadNote);
}
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()) .inflate(R.layout.layout_pdf_adapter, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(final MyViewHolder holder1, final int index) {
final int position = index;
pdfList = pdfModelClasses.get(position);
final DownloadedNotesDataBase databaseNotes = new DownloadedNotesDataBase(context);
holder1.txtBookName.setText(pdfList.getSubjectName().toUpperCase());
holder1.txtBookTitle.setText(StringUtils.getTrimString(pdfList.getTypeName()));
holder1.txtBookBookDateOFIssue.setText(pdfList.getType());
holder1.txtBookCategory.setText(StringUtils.getTrimString(pdfList.getDescription()));
if (databaseNotes.isPurchasedNoteSaved(pdfList.getId(), final_nav_opt_name)) {
holder1.txtDownload.setVisibility(View.VISIBLE);
holder1.layout_download_note_option.setVisibility(View.GONE);
} else {
holder1.txtDownload.setVisibility(View.GONE);
holder1.layout_download_note_option.setVisibility(View.VISIBLE);
}
holder1.layout_open_pdf.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
pdfList = pdfModelClasses.get(position);
holder = holder1;
Log.e("PDFListAdapter", "layout_open_pdf position = "+position);
Log.e("PDFListAdapter", "layout_open_pdf = "+pdfList.getId());
if (databaseNotes.isPurchasedNoteSaved(pdfList.getId(), final_nav_opt_name)) {
DownloadeNotesModel downloadeNotesModel = databaseNotes.getNotesByID(pdfList.getId(), final_nav_opt_name);
Intent intent = new Intent(context, PDFResults.class);
intent.putExtra("pdfList", downloadeNotesModel.getFileLocation());
intent.putExtra("from", "database");
intent.putExtra("getSubjectName", downloadeNotesModel.getSubjectName());
context.startActivity(intent);
} else {
final AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
alertDialog.setTitle("Alert");
alertDialog.setCancelable(true);
alertDialog.setMessage("Notes not downloaded. Do you want to download it?");
alertDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
public void onClick(DialogInterface dialog, int which) {
downloader = new Downloader();
new CheckSpace().execute(pdfList.getFileName());
}
});
alertDialog.show();
}
}
});
holder1.imgDownloadNote.setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
#Override
public void onClick(View v) {
Log.e("PDFListAdapter", "imgDownloadNote position = "+position);
Log.e("PDFListAdapter", "imgDownloadNote = "+pdfList.getId());
pdfList = pdfModelClasses.get(position);
deepak =index ;
holder = holder1;
if (!databaseNotes.isPurchasedNoteSaved(pdfList.getId(), final_nav_opt_name)) {
if (UtilsMethods.isNetworkAvailable(context)) {
int result = ContextCompat.checkSelfPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE);
if (result == PackageManager.PERMISSION_GRANTED) {
downloader = new Downloader();
new CheckSpace().execute(pdfList.getFileName());
} else {
Toast.makeText(context, "storage permission is not granted", Toast.LENGTH_SHORT).show();
PermissionCheck.checkWritePermission(context);
}
} else {
holder.imgDownloadNote.setVisibility(View.GONE);
holder.imgCancelDownloadNote.setVisibility(View.GONE);
holder.progress_download_note.setVisibility(View.GONE);
context.startActivity(new Intent(context, NoInternetActivity.class));
}
}
else Log.e("","Not in db");
}
});
holder1.imgCancelDownloadNote.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.e("PDFListAdapter", "imgCancelDownloadNote position = "+position);
Log.e("PDFListAdapter", "imgCancelDownloadNote = "+pdfList.getId());
final AlertDialog alertDialog = new AlertDialog.Builder(context, R.style.AlertDialogStyle).create();
alertDialog.setTitle("Alert");
alertDialog.setMessage("Are you sure want to cancel download?");
alertDialog.setButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
alertDialog.hide();
downloader.cancel(true);
}
});
alertDialog.show();
}
});
}
#Override
public int getItemCount() {
return pdfModelClasses.size();
}
#Override
public int getItemViewType(int position) {
return position;
}
private void startSave(final Context context, NotesResponseInfo url) {
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
final base_url b = new base_url();
Retrofit.Builder builder = new Retrofit.Builder().baseUrl(b.BASE_URL);
Retrofit retrofit = builder.client(httpClient.build()).build();
AllApis downloadService = retrofit.create(AllApis.class);
Call<ResponseBody> call = downloadService.downloadFileByUrl(StringUtils.getCroppedUrl(url.getFileName()));
call.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, final Response<ResponseBody> response) {
if (response.isSuccessful()) {
mNotifyManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mBuilder = new NotificationCompat.Builder(context);
downloader.execute(response.body());
} else {
}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
t.printStackTrace();
}
});
}
private class Downloader extends AsyncTask<ResponseBody, Integer, Integer> {
#Override
protected void onPreExecute() {
super.onPreExecute();
mBuilder.setContentTitle("Download")
.setContentText("Download in progress")
.setSmallIcon(R.mipmap.lun);
mBuilder.setProgress(100, 0, false);
mNotifyManager.notify(id, mBuilder.build());
}
#Override
protected void onProgressUpdate(Integer... values) {
mBuilder.setContentTitle("Download")
.setContentText("Download in progress")
.setSmallIcon(R.mipmap.ic_logo);
mBuilder.setProgress(100, values[0], false);
mNotifyManager.notify(id, mBuilder.build());
super.onProgressUpdate(values);
}
#Override
protected void onCancelled() {
super.onCancelled();
holder.imgDownloadNote.setVisibility(View.VISIBLE);
holder.imgCancelDownloadNote.setVisibility(View.GONE);
holder.progress_download_note.setVisibility(View.GONE);
mNotifyManager.cancelAll();
}
#Override
protected Integer doInBackground(ResponseBody... params) {
NotesResponseInfo item = new NotesResponseInfo();
item = pdfModelClasses.get(deepak);
ResponseBody body = params[0];
try {
URL url = new URL(pdfList.getFileName());
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setRequestProperty("Accept-Encoding", "identity");
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
ContextWrapper wrapper = new ContextWrapper(getApplicationContext());
int lenghtOfFile = c.getContentLength();
Log.w("getContentLength",""+lenghtOfFile);
File file = wrapper.getDir("PDF", MODE_PRIVATE);
file = new File(file, pdfList.getSubjectName() + "_" + TimeUtils.getCurrentTimeStamp() + ".pdf");
FileOutputStream f = new FileOutputStream(file);
InputStream in = c.getInputStream();
float finalValue = 0;
byte[] buffer = new byte[100 * 1024];
int len1 = 0;
int progress = 0;
long total = 0;
if (!(isCancelled())) {
while ((len1 = in.read(buffer)) >0) {
if (UtilsMethods.isNetworkAvailable(context)) {
f.write(buffer, 0, len1);
total += len1;
setProgress(Integer.parseInt(("" + (int) ((total * 100) / lenghtOfFile))));
/* progress += len1;finalValue = (float) progress/body.contentLength() *100;
setProgress((int) finalValue);
mBuilder.setProgress((int) finalValue,0,false);*/
} else {
File file1 = new File(file.getPath());
file1.delete();
cancel(true);
}
}
new DownloadedNotesDataBase(context).addDonloadedNotesToDatabase(file.getPath(), pdfList);
} else {
File file1 = new File(file.getPath());
file1.delete();
holder.imgDownloadNote.setVisibility(View.VISIBLE);
holder.imgCancelDownloadNote.setVisibility(View.GONE);
holder.progress_download_note.setVisibility(View.GONE);
Toast.makeText(context, "Cancelled", Toast.LENGTH_SHORT).show();
}
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (ProtocolException e1) {
e1.printStackTrace();
} catch (MalformedURLException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Integer result) {
super.onPostExecute(result);
mBuilder.setContentText("Download complete");
mBuilder.setSmallIcon(R.mipmap.ic_logo);
mBuilder.setProgress(100, 100, false);
mNotifyManager.notify(id, mBuilder.build());
holder.txtDownload.setVisibility(View.VISIBLE);
holder.imgDownloadNote.setVisibility(View.GONE);
holder.imgCancelDownloadNote.setVisibility(View.GONE);
holder.progress_download_note.setVisibility(View.GONE);
}
private void setProgress(int progress) {
mBuilder.setContentText("Downloading...")
.setContentTitle(progress + "%")
.setSmallIcon(R.mipmap.ic_logo)
.setOngoing(true)
.setContentInfo(progress + "%")
.setProgress(100, progress, false);
mNotifyManager.notify(id, mBuilder.build());
holder.progress_download_note.setProgress(progress);
}
}
public class CheckSpace extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String file_size = "";
URL url = null;
try {
url = new URL(params[0]);
URLConnection urlConnection = url.openConnection();
urlConnection.connect();
int fileSize = urlConnection.getContentLength();
file_size = UtilsMethods.generateFileSize(fileSize);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return file_size;
}
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
#Override
protected void onPostExecute(String result) {
if (UtilsMethods.compareSpace(result)) {
final AlertDialog alertDialog = new AlertDialog.Builder(context, R.style.AlertDialogStyle).create();
alertDialog.setTitle("Alert");
alertDialog.setMessage("Download this PDF of size " + result + " ?");
alertDialog.setButton("Yes", new DialogInterface.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
public void onClick(DialogInterface dialog, int which) {
alertDialog.hide();
holder.imgDownloadNote.setVisibility(View.GONE);
holder.imgCancelDownloadNote.setVisibility(View.VISIBLE);
holder.progress_download_note.setVisibility(View.VISIBLE);
startSave(context, pdfList);
}
});
alertDialog.show();
} else {
final AlertDialog alertDialog = new AlertDialog.Builder(context, R.style.AlertDialogStyle).create();
alertDialog.setTitle("Alert");
alertDialog.setMessage("Unable to download file. Storage space is not available");
alertDialog.setButton("Ok", new DialogInterface.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
public void onClick(DialogInterface dialog, int which) {
alertDialog.hide();
}
});
alertDialog.show();
}
}
#Override
protected void onPreExecute() {
}
#Override
protected void onProgressUpdate(Void... values) {
}
}
}
I have modified your onBindViewHolder function. The changes are following.
Declared the pdfList variable as final and used it everywhere. It is not necessary to get the pdfList from the pdfModelClasses, each time you use it.
The holder variable is removed, as it is not actually necessary. The holder1 is used everywhere.
There are some changes with the visibility of the buttons. Check holder1.imgDownloadNote.setOnClickListener.
I have found no other problem in your onBindViewHolder. Please let me know if the modified code works.
#Override
public void onBindViewHolder(final MyViewHolder holder1, final int index) {
final int position = index;
// Declare the variable here and make it final.
final PDFList pdfList = pdfModelClasses.get(position);
final DownloadedNotesDataBase databaseNotes = new DownloadedNotesDataBase(context);
holder1.txtBookName.setText(pdfList.getSubjectName().toUpperCase());
holder1.txtBookTitle.setText(StringUtils.getTrimString(pdfList.getTypeName()));
holder1.txtBookBookDateOFIssue.setText(pdfList.getType());
holder1.txtBookCategory.setText(StringUtils.getTrimString(pdfList.getDescription()));
if (databaseNotes.isPurchasedNoteSaved(pdfList.getId(), final_nav_opt_name)) {
holder1.txtDownload.setVisibility(View.VISIBLE);
holder1.layout_download_note_option.setVisibility(View.GONE);
} else {
holder1.txtDownload.setVisibility(View.GONE);
holder1.layout_download_note_option.setVisibility(View.VISIBLE);
}
holder1.layout_open_pdf.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// I have the desired pdfList already, no need to get that again.
// pdfList = pdfModelClasses.get(position);
// Assigning to holder is not necessary.
// holder = holder1;
Log.e("PDFListAdapter", "layout_open_pdf position = "+position);
Log.e("PDFListAdapter", "layout_open_pdf = "+pdfList.getId());
if (databaseNotes.isPurchasedNoteSaved(pdfList.getId(), final_nav_opt_name)) {
DownloadeNotesModel downloadeNotesModel = databaseNotes.getNotesByID(pdfList.getId(), final_nav_opt_name);
Intent intent = new Intent(context, PDFResults.class);
intent.putExtra("pdfList", downloadeNotesModel.getFileLocation());
intent.putExtra("from", "database");
intent.putExtra("getSubjectName", downloadeNotesModel.getSubjectName());
context.startActivity(intent);
} else {
final AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
alertDialog.setTitle("Alert");
alertDialog.setCancelable(true);
alertDialog.setMessage("Notes not downloaded. Do you want to download it?");
alertDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
public void onClick(DialogInterface dialog, int which) {
downloader = new Downloader();
new CheckSpace().execute(pdfList.getFileName());
}
});
alertDialog.show();
}
}
});
holder1.imgDownloadNote.setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
#Override
public void onClick(View v) {
Log.e("PDFListAdapter", "imgDownloadNote position = "+position);
Log.e("PDFListAdapter", "imgDownloadNote = "+pdfList.getId());
pdfList = pdfModelClasses.get(position);
deepak =index ;
// We don't need the reassignment.
// holder = holder1;
if (!databaseNotes.isPurchasedNoteSaved(pdfList.getId(), final_nav_opt_name)) {
if (UtilsMethods.isNetworkAvailable(context)) {
int result = ContextCompat.checkSelfPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE);
if (result == PackageManager.PERMISSION_GRANTED) {
downloader = new Downloader();
new CheckSpace().execute(pdfList.getFileName());
// Make them visible when the internet connection is there.
holder1.imgDownloadNote.setVisibility(View.VISIBLE);
holder1.imgCancelDownloadNote.setVisibility(View.VISIBLE);
holder1.progress_download_note.setVisibility(View.VISIBLE);
} else {
Toast.makeText(context, "storage permission is not granted", Toast.LENGTH_SHORT).show();
PermissionCheck.checkWritePermission(context);
holder1.imgDownloadNote.setVisibility(View.GONE);
holder1.imgCancelDownloadNote.setVisibility(View.GONE);
holder1.progress_download_note.setVisibility(View.GONE);
}
} else {
holder1.imgDownloadNote.setVisibility(View.GONE);
holder1.imgCancelDownloadNote.setVisibility(View.GONE);
holder1.progress_download_note.setVisibility(View.GONE);
context.startActivity(new Intent(context, NoInternetActivity.class));
}
} else {
// Put proper visibility everywhere.
holder1.imgDownloadNote.setVisibility(View.GONE);
holder1.imgCancelDownloadNote.setVisibility(View.GONE);
holder1.progress_download_note.setVisibility(View.GONE);
Log.e("","Not in db");
}
}
});
holder1.imgCancelDownloadNote.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.e("PDFListAdapter", "imgCancelDownloadNote position = "+position);
Log.e("PDFListAdapter", "imgCancelDownloadNote = "+pdfList.getId());
final AlertDialog alertDialog = new AlertDialog.Builder(context, R.style.AlertDialogStyle).create();
alertDialog.setTitle("Alert");
alertDialog.setMessage("Are you sure want to cancel download?");
alertDialog.setButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
alertDialog.hide();
downloader.cancel(true);
}
});
alertDialog.show();
}
});
}
#Override
public int getItemCount() {
return pdfModelClasses.size();
}
#Override
public int getItemViewType(int position) {
return position;
}

How to open the particular fragment on the click of the push notification message in the notification tab?

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.
}
}

Video and audio call 2 Android devices - webrtc

I'm trying do develop Android app which will send audio and video via webrtc protocol between devices. This code works well with Android and web interface, but not between two Androids. Every time connection is opened and popup says that devices are connected, but there is no sound and picture. I tried a lot of things, but nothing helped. Dependencies and permissions are ok. Used my own pub and sub keys from PubNub. It opens connection 1 of 20 times between two Androids, so I think that something isn't working well here.
Followed this tutorial to create app: tutorial
I found this error image
Camera is crashing somewhere, but I really don't know why.
public static final String VIDEO_TRACK_ID = "videoPN";
public static final String AUDIO_TRACK_ID = "audioPN";
public static final String LOCAL_MEDIA_STREAM_ID = "localStreamPN";
private PnRTCClient pnRTCClient;
private VideoSource localVideoSource;
private VideoRenderer.Callbacks localRender;
private VideoRenderer.Callbacks remoteRender;
private GLSurfaceView mVideoView;
private String username;
private class MyRTCListener extends PnRTCListener {
#Override
public void onLocalStream(final MediaStream localStream) {
VideoChatActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
if(localStream.videoTracks.size()==0) return;
localStream.videoTracks.get(0).addRenderer(new VideoRenderer(localRender));
}
});
}
#Override
public void onAddRemoteStream(final MediaStream remoteStream, final PnPeer peer) {
VideoChatActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(VideoChatActivity.this,"Connected to " + peer.getId(), Toast.LENGTH_SHORT).show();
try {
if(remoteStream.videoTracks.size()==0) return;
remoteStream.videoTracks.get(0).addRenderer(new VideoRenderer(remoteRender));
VideoRendererGui.update(remoteRender, 0, 0, 100, 100, VideoRendererGui.ScalingType.SCALE_ASPECT_FILL, false);
VideoRendererGui.update(localRender, 72, 72, 25, 25, VideoRendererGui.ScalingType.SCALE_ASPECT_FIT, true);
}
catch (Exception e){ e.printStackTrace(); }
}
});
}
#Override
public void onPeerConnectionClosed(PnPeer peer) {
Intent intent = new Intent(VideoChatActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.videochatactivity);
Bundle extras = getIntent().getExtras();
if (extras == null || !extras.containsKey(Constants.USER_NAME)) {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
Toast.makeText(this, "Need to pass username to VideoChatActivity in intent extras (Constants.USER_NAME).",
Toast.LENGTH_SHORT).show();
finish();
return;
}
this.username = extras.getString(Constants.USER_NAME, "");
PeerConnectionFactory.initializeAndroidGlobals(
this, // Context
true, // Audio Enabled
true, // Video Enabled
true, // Hardware Acceleration Enabled
null); // Render EGL Context
PeerConnectionFactory pcFactory = new PeerConnectionFactory();
this.pnRTCClient = new PnRTCClient(Constants.PUB_KEY, Constants.SUB_KEY, this.username);
int camNumber = VideoCapturerAndroid.getDeviceCount();
String frontFacingCam = VideoCapturerAndroid.getNameOfFrontFacingDevice();
String backFacingCam = VideoCapturerAndroid.getNameOfBackFacingDevice();
VideoCapturerAndroid capturer = (VideoCapturerAndroid) VideoCapturerAndroid.create(frontFacingCam);
localVideoSource = pcFactory.createVideoSource(capturer, this.pnRTCClient.videoConstraints());
VideoTrack localVideoTrack = pcFactory.createVideoTrack(VIDEO_TRACK_ID, localVideoSource);
AudioSource audioSource = pcFactory.createAudioSource(this.pnRTCClient.audioConstraints());
AudioTrack localAudioTrack = pcFactory.createAudioTrack(AUDIO_TRACK_ID, audioSource);
MediaStream mediaStream = pcFactory.createLocalMediaStream(LOCAL_MEDIA_STREAM_ID);
mediaStream.addTrack(localVideoTrack);
mediaStream.addTrack(localAudioTrack);
this.mVideoView = (GLSurfaceView) findViewById(R.id.gl_surface);
VideoRendererGui.setView(mVideoView, null);
remoteRender = VideoRendererGui.create(0, 0, 100, 100, VideoRendererGui.ScalingType.SCALE_ASPECT_FILL, false);
localRender = VideoRendererGui.create(0, 0, 100, 100, VideoRendererGui.ScalingType.SCALE_ASPECT_FILL, true);
this.pnRTCClient.attachRTCListener(new MyRTCListener());
this.pnRTCClient.attachLocalMediaStream(mediaStream);
this.pnRTCClient.listenOn(this.username);
this.pnRTCClient.setMaxConnections(1);
if (extras.containsKey(Constants.JSON_CALL_USER)) {
String callUser = extras.getString(Constants.JSON_CALL_USER, "");
connectToUser(callUser);
}
}
public void connectToUser(String user) {
this.pnRTCClient.connect(user);
}
public void hangup(View view) {
this.pnRTCClient.closeAllConnections();
startActivity(new Intent(VideoChatActivity.this, MainActivity.class));
}
#Override
protected void onDestroy() {
super.onDestroy();
if (this.localVideoSource != null) {
localVideoSource.stop();
}
if (this.pnRTCClient != null) {
this.pnRTCClient.onDestroy();
this.pnRTCClient.closeAllConnections();
}
}
Here is MainActivity if it will help:
private SharedPreferences mSharedPreferences;
private TextView mUsernameTV;
private EditText mCallNumET;
// private Pubnub mPubNub;
private String username;
private Pubnub mPubNub;
public void initPubNub() {
String stdbyChannel = this.username + Constants.STDBY_SUFFIX;
this.mPubNub = new Pubnub(Constants.PUB_KEY, Constants.SUB_KEY);
this.mPubNub.setUUID(this.username);
try {
this.mPubNub.subscribe(stdbyChannel, new Callback() {
#Override
public void successCallback(String channel, Object message) {
Log.d("MA-success", "MESSAGE: " + message.toString());
if (!(message instanceof JSONObject)) return; // Ignore if not JSONObject
JSONObject jsonMsg = (JSONObject) message;
try {
if (!jsonMsg.has(Constants.JSON_CALL_USER)) return;
String user = jsonMsg.getString(Constants.JSON_CALL_USER);
// Consider Accept/Reject call here
Intent intent = new Intent(MainActivity.this, VideoChatActivity.class);
intent.putExtra(Constants.USER_NAME, username);
intent.putExtra(Constants.JSON_CALL_USER, user);
startActivity(intent);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
} catch (PubnubException e) {
e.printStackTrace();
}
}
public void makeCall(View view){
String callNum = mCallNumET.getText().toString();
if (callNum.isEmpty() || callNum.equals(this.username)) {
Toast.makeText(this, "Enter a valid number.", Toast.LENGTH_SHORT).show();
}
dispatchCall(callNum);
}
public void dispatchCall(final String callNum) {
final String callNumStdBy = callNum + Constants.STDBY_SUFFIX;
JSONObject jsonCall = new JSONObject();
try {
jsonCall.put(Constants.JSON_CALL_USER, this.username);
mPubNub.publish(callNumStdBy, jsonCall, new Callback() {
#Override
public void successCallback(String channel, Object message) {
Log.d("MA-dCall", "SUCCESS: " + message.toString());
Intent intent = new Intent(MainActivity.this, VideoChatActivity.class);
intent.putExtra(Constants.USER_NAME, username);
intent.putExtra(Constants.JSON_CALL_USER, callNum);
startActivity(intent);
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.mSharedPreferences = getSharedPreferences(Constants.SHARED_PREFS, MODE_PRIVATE);
// Return to Log In screen if no user is logged in.
if (!this.mSharedPreferences.contains(Constants.USER_NAME)){
Intent intent = new Intent(this, LoginActivity.class);
startActivity(intent);
finish();
return;
}
this.username = this.mSharedPreferences.getString(Constants.USER_NAME, "");
this.mCallNumET = (EditText) findViewById(R.id.call_num);
this.mUsernameTV = (TextView) findViewById(R.id.main_username);
this.mUsernameTV.setText(this.username); // Set the username to the username text view
//TODO: Create and instance of Pubnub and subscribe to standby channel
// In pubnub subscribe callback, send user to your VideoActivity
initPubNub();
}
I will appreciate any help. Thanks to everybody.
when You run your application that time they ask sign in usename
that time you wrote your name
put that name in VideoChatActivity class
this.pnRTCClient.listenOn("your name when your wrote at signin time");
this.pnRTCClient.setMaxConnections(3);

Categories

Resources