I'm looking to create an app to whatsapp in which i need to launch a window with smileyset (like chathead in facebook messenger) .I did it but when i opened whatsapp conversation a small button of smiley set will displayed and it wont disappear when I close the whatsapp.
how i can implement this?
this is the service which uses for input smilies
public class SmileyInputService extends Service {
private WindowManager windowManager;
private List<View> chatHeads;
int f=0;
private LayoutInflater inflater;
#Override
public void onCreate() {
super.onCreate();
windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
inflater = LayoutInflater.from(this);
chatHeads = new ArrayList<View>();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
final WindowManager.LayoutParams params = new WindowManager.LayoutParams(WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.TYPE_PHONE, WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE, PixelFormat.TRANSLUCENT);
if(chatHeads.isEmpty()) {
final View chatHead = inflater.inflate(R.layout.service_smile_head, null);
chatHead.findViewById(R.id.btn_dismiss).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
removeChatHead(chatHead);
}
});
chatHead.findViewById(R.id.txt_title).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(f==0) {
chatHead.findViewById(R.id.smilieylisting).setVisibility(LinearLayout.VISIBLE);
f=1;
}
else {
chatHead.findViewById(R.id.smilieylisting).setVisibility(LinearLayout.GONE);
f=0;
}} };
chatHead.findViewById(R.id.happyhead).setOnClickListener(new View.OnClickListener() {
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
#Override
public void onClick(View view) {
ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("label","[happy]");
clipboard.setPrimaryClip(clip);
}
});
chatHead.findViewById(R.id.kisshead).setOnClickListener(new View.OnClickListener() {
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
#Override
public void onClick(View view) {
ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("label","[kiss]");
clipboard.setPrimaryClip(clip);
}
});
params.gravity=Gravity.LEFT|Gravity.TOP;
addChatHead(chatHead, params);
}
return super.onStartCommand(intent, flags, startId);
}
public void addChatHead(View chatHead, WindowManager.LayoutParams params) {
chatHeads.add(chatHead);
windowManager.addView(chatHead, params);
}
public void removeChatHead(View chatHead) {
chatHeads.remove(chatHead);
windowManager.removeView(chatHead);
}
#Override
public void onDestroy() {
super.onDestroy();
for (View chatHead : chatHeads) {
removeChatHead(chatHead);
}
}
}
here is my accessibility service for listening event
Public class ListeningSmileyService extends AccessibilityService {
AccessibilityServiceInfo info = new AccessibilityServiceInfo();
public static String currentsmiley;
#Override
public void onServiceConnected() {
info.eventTypes = AccessibilityEvent.TYPE_VIEW_CLICKED| AccessibilityEvent.TYPE_VIEW_FOCUSED| AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED |AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED;
info.packageNames = new String[]
{"com.whatsapp"};
info.feedbackType = AccessibilityServiceInfo.FEEDBACK_ALL_MASK;
info.notificationTimeout = 100;
this.setServiceInfo(info);
}
#Override
public void onAccessibilityEvent(AccessibilityEvent event) {
Log.i("event!","clix");
final int eventType = event.getEventType();
String eventText = null;
switch(eventType) {
case AccessibilityEvent.TYPE_VIEW_CLICKED:
if(!event.getClassName().equals("android.widget.EditText"))
stopService(new Intent(getApplicationContext(),SmileyInputService.class));
eventText = "Clix: ";
break;
case AccessibilityEvent.TYPE_VIEW_FOCUSED |AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED:
stopService(new Intent(getApplicationContext(),SmileyInputService.class));
eventText = "Focused: ";
break;
case AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED:
stopService(new Intent(getApplicationContext(),SmileyInputService.class));
break;
}
if(event.getClassName().equals("android.widget.EditText")){
Log.i("sha","log");
Intent i=new Intent(getApplicationContext(),SmileyInputService.class);
startService(i);
}
}
}
Related
The problem is that I am trying to pass the name of the user when the adReward is complete to another activity. But I'm stuck in this activity, even though the video ad is loaded. (and it works well while there are no video ad to show). Here is my code:
My java.class
public class TheDay1 extends AppCompatActivity implements RewardedVideoAdListener {
Vibrator vibrator;
private RewardedVideoAd HDay1;
int currentActivity = 0;
boolean flag;
private EditText vname;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_the_day1);
vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
MobileAds.initialize(this,
"ca-app-pub-3940256099942544/6300978111");
///ADD BAN
AdView mAdView = findViewById(R.id.banner1);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
///////////////////////////////////
//VIDEO
HDay1 = MobileAds.getRewardedVideoAdInstance(this);
HDay1.setRewardedVideoAdListener(this);
loadRewardedVideoDAY1();
vname = findViewById(R.id.name);
final ImageView nm = findViewById(R.id.ID);
nm.setVisibility(View.INVISIBLE);
ColorMatrix matrix = new ColorMatrix();
matrix.setSaturation(0);
ColorMatrixColorFilter filter = new ColorMatrixColorFilter(matrix);
nm.setColorFilter(filter);
final Button closeAd = findViewById(R.id.closeDay1);
closeAd.setVisibility(View.INVISIBLE);
///////////////////////////////////////////////////////////////////////////////////////////
closeAd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
vibrator.vibrate(50);
loadRewardedVideoDAY1();
if (HDay1.isLoaded()) {
HDay1.show();
setCurrent(1);
}
String name = vname.getText().toString();
getusername(name);
}
});
}
////////////////////////////////////////////////////////////////
private void Day1() {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
private void getusername(String name) {
Intent intent = new Intent(this, ActivityTwo.class);
Resources resources = getResources();
String key = resources.getString(R.string.key_name);
intent.putExtra(key, name);
startActivity(intent);
}
private void loadRewardedVideoDAY1() {
if (!HDay1.isLoaded()) {
HDay1 = null;
HDay1 = MobileAds.getRewardedVideoAdInstance(this);
HDay1.setRewardedVideoAdListener(this);
///////////////TEST ID//////////////////
HDay1.loadAd("ca-app-pub-3940256099942544/5224354917", new AdRequest.Builder().build());
}
}
#Override
public void onRewardedVideoAdLoaded() {
Log.d("LOADED!", "onRewardedVideoAdLoaded");
}
#Override
public void onRewardedVideoAdOpened() {
Log.d("OPENED!", "onRewardedVideoAdLoaded");
}
#Override
public void onRewardedVideoStarted() {
Log.d("STARTED!", "onRewardedVideoAdLoaded");
}
#Override
public void onRewardedVideoAdClosed() {
loadRewardedVideoDAY1();
if (currentActivity == 1) {
Day1();
}
}
#Override
public void onRewarded(RewardItem rewardItem) {
loadRewardedVideoDAY1();
flag = true;
if (currentActivity == 1) {
Day1();
}
}
#Override
public void onRewardedVideoAdLeftApplication() {
}
#Override
public void onRewardedVideoAdFailedToLoad(int i) {
}
#Override
public void onRewardedVideoCompleted() {
}
#Override
protected void onPause() {
HDay1.pause(this);
super.onPause();
}
#Override
protected void onResume() {
super.onResume();
}
public void setCurrent(int val){
currentActivity = val;
}
Any idea what the problem could be? Thanks in advance
Try below code. Update ProcessData with your intent logic and update oncreate with other data required in your class
public class TheDay1 extends AppCompatActivity implements RewardedVideoAdListener {
private RewardedVideoAd mRewardedVideoAd;
private Boolean bRewardVideo = false;
#Override
public void onResume() {
super.onResume();
if (mRewardedVideoAd != null) {
mRewardedVideoAd.resume(this);
}
}
#Override
public void onPause() {
super.onPause();
if (mRewardedVideoAd != null) {
mRewardedVideoAd.pause(this);
}
}
#Override
public void onDestroy() {
super.onDestroy();
if (mRewardedVideoAd != null) {
mRewardedVideoAd.destroy(this);
}
}
#Override
public void onRewardedVideoCompleted() {
//Toast.makeText(this, "onRewardedVideoCompleted", Toast.LENGTH_SHORT).show();
}
#Override
public void onRewardedVideoAdLoaded() {
//Toast.makeText(this, "onRewardedVideoAdLoaded", Toast.LENGTH_SHORT).show();
}
#Override
public void onRewardedVideoAdOpened() {
//Toast.makeText(this, "onRewardedVideoAdOpened", Toast.LENGTH_SHORT).show();
}
#Override
public void onRewardedVideoStarted() {
//Toast.makeText(this, "onRewardedVideoStarted", Toast.LENGTH_SHORT).show();
}
#Override
public void onRewardedVideoAdClosed() {
//Toast.makeText(this, "Reward Video Closed", Toast.LENGTH_SHORT).show();
// Load the next rewarded video ad.
if (bRewardVideo) {
ProcessData();
} else {
Toast.makeText(this, "Please View Reward Video to get Reward Points", Toast.LENGTH_LONG).show();
}
loadRewardedVideoAd();
}
#Override
public void onRewarded(RewardItem rewardItem) {
Toast.makeText(this, "Now you can close Ad to Process", Toast.LENGTH_LONG).show();
bRewardVideo = true;
}
#Override
public void onRewardedVideoAdLeftApplication() {
//Toast.makeText(this, "onRewardedVideoAdLeftApplication",Toast.LENGTH_SHORT).show();
}
#Override
public void onRewardedVideoAdFailedToLoad(int i) {
Toast.makeText(this, "Fail to Load Reward Video. Please try again!", Toast.LENGTH_SHORT).show();
}
private void loadRewardedVideoAd() {
bRewardVideo = false;
mRewardedVideoAd.loadAd(BuildConfig.REWARDVIDEOID,
new AdRequest.Builder().build());
}
private void ProcessData() {
Snackbar.make(findViewById(R.id.drawer_layout_law), "Please wait while we process the request... ", Snackbar.LENGTH_INDEFINITE).show();
//WRITE YOUR INTENT CODE HERE
Intent intent = new Intent(this, ActivityTwo.class);
Resources resources = getResources();
String key = resources.getString(R.string.key_name);
intent.putExtra(key, name);
startActivity(intent);
}
private void ShowRewardVideoDialog() {
if (mRewardedVideoAd.isLoaded()) {
mRewardedVideoAd.show();
} else {
loadRewardedVideoAd();
Toast.makeText(mctx, "Fail to Load Reward Video : Please try again", Toast.LENGTH_LONG).show();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mRewardedVideoAd = MobileAds.getRewardedVideoAdInstance(this);
mRewardedVideoAd.setRewardedVideoAdListener(this);
loadRewardedVideoAd();
}
}
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'm trying to play video on player and the video is url that I fetch from an api
so I have a channels in recycleview1 and when I click on one channel the channel start play in new activity
in that activity the player take half of screen and the rest is for recycleview2 which contain some channels for easy and fast navigate between channels
so when I open the channel from recycleview1 and it start playing then I rotate the screen to landscape it work fine then restore the screen to portrate again the channel still working
but the problem is when I click on channel from recycleview2 which lead to update the url that already played and start the new one
so each time I click on channel from recycleview2 the videoview updated to new channel url that clicked
I face problem when I rotate the screen after played channel from recycleview2 the videoview start play a channel that I clicked from recyclewview1 before clicking on new channel from recycleview2 because it return to onCreate method which build the url depend on the information passed with on click
so I used to save the instance state of url so when I rotate the screen to landscape the vidoeview still played the last channel that played
but the problem is when I re rotate the screen to portrate again the videoview here return to the first channel played when start the activity
I tried to save instance state too but it doesn't working
this is the code:
public class TVChannel extends AppCompatActivity implements
TVAdapter.TVAdapterOnClickHandler {
private VideoView videoView;
private int position = 0;
private String video;
private MediaController mediaController;
String mChannelTitle;
String mChannelApp;
String mChannelStreamname;
String mChannelCat;
TVAdapter mAdapter;
RecyclerView mSportsList;
private TextView mCategory;
private TextView mErrorMessageDisplay;
private ProgressBar mLoadingIndicator;
Context mContext ;
public TVItem channelObject;
Uri vidUri;
String myBoolean;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
setContentView(R.layout.activity_tv_channel);
ButterKnife.bind(this);
mSportsList = (RecyclerView) findViewById(R.id.rv_channel);
mErrorMessageDisplay = (TextView) findViewById(R.id.tv_error_message_display);
mContext = this;
channelObject = getIntent().getParcelableExtra("TVChannel");
if (channelObject != null) {
mChannelTitle = String.valueOf(channelObject.getTitle());
mChannelApp = String.valueOf(channelObject.getApp());
mChannelStreamname = String.valueOf(channelObject.getStreamName());
mChannelCat = String.valueOf(channelObject.getCat());
}
mCategory = (TextView) findViewById(R.id.category);
videoView = (VideoView) findViewById(R.id.videoView);
String host = "http://ip/";
String app = mChannelApp;
String streamname = mChannelStreamname;
String playlist = "playlist.m3u8";
vidUri = Uri.parse(host).buildUpon()
.appendPath(app)
.appendPath(streamname)
.appendPath(playlist)
.build();
videoView.setVideoURI(vidUri);
final PlayerControlView playerControlView = (PlayerControlView) findViewById(R.id.player_control_view);
playerControlView.setAlwaysShow(true);
PlayerControlView.ViewHolder viewHolder = playerControlView.getViewHolder();
viewHolder.pausePlayButton.setPauseDrawable(ContextCompat.getDrawable(this, R.drawable.pause));
viewHolder.pausePlayButton.setPlayDrawable(ContextCompat.getDrawable(this, R.drawable.play));
viewHolder.controlsBackground.setBackgroundColor(ContextCompat.getColor(this, R.color.colorPrimaryDark));
viewHolder.currentTimeText.setTextColor(ContextCompat.getColor(this, R.color.colorAccent));
// viewHolder.totalTimeText.setTextSize(18);
playerControlView.setNextListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(TVChannel.this, "onClick Next", Toast.LENGTH_SHORT).show();
}
});
playerControlView.setPrevListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(TVChannel.this, "onClick Prev", Toast.LENGTH_SHORT).show();
}
});
mediaController = playerControlView.getMediaControllerWrapper();
videoView.setMediaController(mediaController);
videoView.seekTo(position);
videoView.start();
videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
playerControlView.show();
}
});
GridLayoutManager LayoutManagerSports = new GridLayoutManager(this, 3);
mSportsList.setLayoutManager(LayoutManagerSports);
mSportsList.setHasFixedSize(true);
mAdapter = new TVAdapter(this, mContext);
mSportsList.setAdapter(mAdapter);
mLoadingIndicator = (ProgressBar) findViewById(R.id.pb_loading_indicator);
String sortchannels = mChannelCat.toLowerCase() + ".php";
loadTVData(sortchannels);
} else {
setContentView(R.layout.activity_tv_channel2);
ButterKnife.bind(this);
mSportsList = (RecyclerView) findViewById(R.id.rv_channel);
mErrorMessageDisplay = (TextView) findViewById(R.id.tv_error_message_display);
mContext = this;
channelObject = getIntent().getParcelableExtra("TVChannel");
if (channelObject != null) {
mChannelTitle = String.valueOf(channelObject.getTitle());
mChannelApp = String.valueOf(channelObject.getApp());
mChannelStreamname = String.valueOf(channelObject.getStreamName());
mChannelCat = String.valueOf(channelObject.getCat());
}
mCategory = (TextView) findViewById(R.id.category);
videoView = (VideoView) findViewById(R.id.videoView);
if (savedInstanceState != null){
myBoolean = savedInstanceState.getString("video");
Toast.makeText(this, "This is my Toast message!",
Toast.LENGTH_LONG).show();
videoView.setVideoURI(Uri.parse(myBoolean));
}
else {
String host = "http://ip/";
String app = mChannelApp;
String streamname = mChannelStreamname;
String playlist = "playlist.m3u8";
vidUri = Uri.parse(host).buildUpon()
.appendPath(app)
.appendPath(streamname)
.appendPath(playlist)
.build();
videoView.setVideoURI(vidUri);
}
final PlayerControlView playerControlView = (PlayerControlView) findViewById(R.id.player_control_view);
playerControlView.setAlwaysShow(false);
PlayerControlView.ViewHolder viewHolder = playerControlView.getViewHolder();
viewHolder.pausePlayButton.setPauseDrawable(ContextCompat.getDrawable(this, R.drawable.pause));
viewHolder.pausePlayButton.setPlayDrawable(ContextCompat.getDrawable(this, R.drawable.play));
viewHolder.controlsBackground.setBackgroundColor(ContextCompat.getColor(this, R.color.controlBackground));
viewHolder.currentTimeText.setTextColor(ContextCompat.getColor(this, R.color.colorAccent));
// viewHolder.totalTimeText.setTextSize(18);
playerControlView.setNextListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(TVChannel.this, "onClick Next", Toast.LENGTH_SHORT).show();
}
});
playerControlView.setPrevListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(TVChannel.this, "onClick Prev", Toast.LENGTH_SHORT).show();
}
});
mediaController = playerControlView.getMediaControllerWrapperFullScreen();
videoView.setMediaController(mediaController);
videoView.seekTo(position);
videoView.start();
videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
playerControlView.show();
}
});
GridLayoutManager LayoutManagerSports = new GridLayoutManager(this, 3);
mSportsList.setLayoutManager(LayoutManagerSports);
mSportsList.setHasFixedSize(true);
mAdapter = new TVAdapter(this, mContext);
mSportsList.setAdapter(mAdapter);
mLoadingIndicator = (ProgressBar) findViewById(R.id.pb_loading_indicator);
String sortchannels = mChannelCat.toLowerCase() + ".php";
loadTVData(sortchannels);
}
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
// Store current position.
savedInstanceState.putString("video", String.valueOf(vidUri));
videoView.start();
}
// After rotating the phone. This method is called.
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// Get saved position.
video = savedInstanceState.getString("video");
videoView.start();
}
private void loadTVData(String sortChannels) {
showTVDataView();
new FetchTVTask().execute(sortChannels);
}
#Override
public void onClick(TVItem channel, View view) {
if (channel != null) {
mChannelTitle = String.valueOf(channel.getTitle());
mChannelApp = String.valueOf(channel.getApp());
mChannelStreamname = String.valueOf(channel.getStreamName());
}
String host = "http://ip/";
String app = mChannelApp;
String streamname = mChannelStreamname;
String playlist = "playlist.m3u8";
vidUri = Uri.parse(host).buildUpon()
.appendPath(app)
.appendPath(streamname)
.appendPath(playlist)
.build();
videoView.setVideoURI(vidUri);
final PlayerControlView playerControlView = (PlayerControlView) findViewById(R.id.player_control_view);
playerControlView.setAlwaysShow(true);
PlayerControlView.ViewHolder viewHolder = playerControlView.getViewHolder();
viewHolder.pausePlayButton.setPauseDrawable(ContextCompat.getDrawable(this, R.drawable.pause));
viewHolder.pausePlayButton.setPlayDrawable(ContextCompat.getDrawable(this, R.drawable.play));
viewHolder.controlsBackground.setBackgroundColor(ContextCompat.getColor(this, R.color.colorPrimaryDark));
viewHolder.currentTimeText.setTextColor(ContextCompat.getColor(this, R.color.colorAccent));
// viewHolder.totalTimeText.setTextSize(18);
playerControlView.setNextListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(TVChannel.this, "onClick Next", Toast.LENGTH_SHORT).show();
}
});
playerControlView.setPrevListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(TVChannel.this, "onClick Prev", Toast.LENGTH_SHORT).show();
}
});
videoView.setMediaController(playerControlView.getMediaControllerWrapper());
//
videoView.seekTo(position);
videoView.start();
videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
playerControlView.show();
}
});
}
private void showTVDataView() {
mErrorMessageDisplay.setVisibility(View.INVISIBLE);
mSportsList.setVisibility(View.VISIBLE);
}
private void showErrorMessage() {
mSportsList.setVisibility(View.INVISIBLE);
mErrorMessageDisplay.setVisibility(View.VISIBLE);
}
public class FetchTVTask extends AsyncTask<String, Void, ArrayList<TVItem>> {
#Override
protected void onPreExecute() {
super.onPreExecute();
mLoadingIndicator.setVisibility(View.VISIBLE);
}
#Override
protected ArrayList<TVItem> doInBackground(String... params) {
if (params.length == 0) {
return null;
}
String sortChannels = params[0];
URL channelRequestUrl = NetworkTV.buildUrl(sortChannels);
try {
String jsonTVResponse = NetworkTV.getResponseFromHttpUrl(channelRequestUrl);
ArrayList<TVItem> simpleJsonTVData = JsonTV.getSimpleTVStringsFromJson(TVChannel.this, jsonTVResponse);
return simpleJsonTVData;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
#Override
protected void onPostExecute(ArrayList<TVItem> TVData) {
mLoadingIndicator.setVisibility(View.INVISIBLE);
mCategory.setText(TVData.get(0).getCat());
if (TVData != null) {
showTVDataView();
mAdapter.setTVData(TVData);
} else {
showErrorMessage();
}
}
}
}
you can see that I use:
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
}
else{
}
to set content view for portrait and landscape
and inside else this is the code that I use to save the url in landscape mode:
if (savedInstanceState != null){
myBoolean = savedInstanceState.getString("video");
Toast.makeText(this, "This is my Toast message!",
Toast.LENGTH_LONG).show();
videoView.setVideoURI(Uri.parse(myBoolean));
}
else {
String host = "http://ip/";
String app = mChannelApp;
String streamname = mChannelStreamname;
String playlist = "playlist.m3u8";
vidUri = Uri.parse(host).buildUpon()
.appendPath(app)
.appendPath(streamname)
.appendPath(playlist)
.build();
videoView.setVideoURI(vidUri);
}
and if savedInstanceState null so build url like this from on click information that I pass in portrait mode:
channelObject = getIntent().getParcelableExtra("TVChannel");
if (channelObject != null) {
mChannelTitle = String.valueOf(channelObject.getTitle());
mChannelApp = String.valueOf(channelObject.getApp());
mChannelStreamname = String.valueOf(channelObject.getStreamName());
mChannelCat = String.valueOf(channelObject.getCat());
}
how can I save the url channel when I re rotate screen from landscape to portrait mode again?
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.
I am making a game app but the music still keeps playing even when I closed the game. how to stop? and how to change background music once I go to another activity after I clicked a button
public class BackgroundSoundService extends Service {
private static final String TAG = null;
MediaPlayer player;
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
player = MediaPlayer.create(this, R.raw.rysk);
player.setLooping(true); // Set looping
player.setVolume(100,100);
}
public int onStartCommand(Intent intent, int flags, int startId) {
player.start();
return 1;
}
public void onStart(Intent intent, int startId) {
// TO DO
}
public IBinder onUnBind(Intent arg0) {
// TO DO Auto-generated method
return null;
}
public void onStop() {
}
public void onPause() {
}
#Override
public void onDestroy() {
player.stop();
player.release();
}
#Override
public void onLowMemory() {
}
}
this is my main activity (PlayActivity.class)
Intent svc=new Intent(this, BackgroundSoundService.class);
startService(svc);
I want to change the music when I clicked a button and went to CatActivity
You should have to work with registerReceiver,unregisterReceiver.
May this helps you.
MainActivity.java
public class MainActivity extends AppCompatActivity {
private Button btn_startservice;
private Button btn_stopservice;
private TextView tv_servicecounter;
ServiceDemo myService;
boolean isBound;
BroadcastReceiver broadcastRec = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
int datapassed = intent.getIntExtra("value", 0);
tv_servicecounter.setText(String.valueOf(datapassed));
}
};
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv_servicecounter = (TextView) findViewById(R.id.tv_activity_main_count);
btn_startservice = (Button) findViewById(R.id.btn_activity_main_startservices);
btn_stopservice = (Button) findViewById(R.id.btn_activity_main_stopservices);
btn_startservice.setOnClickListener(
new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
#Override
public void onClick(View v) {
Intent objIntent = new Intent(MainActivity.this, ServiceDemo.class);
if (!isBound) {
bindService(objIntent, myConnection, Context.BIND_AUTO_CREATE);
isBound = true;
startService(objIntent);
} else {
isBound = false;
unbindService(myConnection);
}
}
}
);
btn_stopservice.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent objIntent = new Intent(MainActivity.this, ServiceDemo.class);
if (isBound) {
isBound = false;
unbindService(myConnection);
stopService(objIntent);
} else {
stopService(objIntent);
}
}
}
);
}
#Override
protected void onResume() {
registerReceiver(broadcastRec, new IntentFilter("USER_ACTION"));
super.onResume();
}
#Override
protected void onStop() {
this.unregisterReceiver(broadcastRec);
super.onStop();
}
private ServiceConnection myConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className,
IBinder service) {
myService = ((ServiceDemo.MyLocalBinder) service).getService();
isBound = true;
}
public void onServiceDisconnected(ComponentName arg0) {
isBound = false;
}
};
#Override
protected void onDestroy() {
super.onDestroy();
if (isBound) {
unbindService(myConnection);
isBound = false;
}
}
}
And ServiceDemo.java
public class ServiceDemo extends Service {
int i;
private MyThread mythread;
public boolean isRunning = false;
Notification notification;
#Override
public void onCreate() {
super.onCreate();
Log.d(TAG, "onCreate");
mythread = new MyThread();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "Service Started", Toast.LENGTH_SHORT).show();
if (!isRunning) {
mythread.start();
isRunning = true;
}
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
mythread.interrupt();
Toast.makeText(this, "Service Destroyed", Toast.LENGTH_SHORT).show();
}
public void sendBrodcastMsg(int value) {
Intent intent = new Intent();
intent.setAction("USER_ACTION");
intent.putExtra("value", value);
sendBroadcast(intent);
}
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
class MyThread extends Thread {
static final long DELAY = 100;
#Override
public void run() {
while (isRunning) {
try {
i++;
Thread.sleep(DELAY);
sendBrodcastMsg(i);
shownotification();
} catch (InterruptedException e) {
isRunning = false;
e.printStackTrace();
}
}
stopSelf();
}
}
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
public void shownotification() {
Intent in = new Intent(this, MainActivity.class);
PendingIntent pIntent = PendingIntent.getActivity(this, (int) System.currentTimeMillis(), in, 0);
notification = new NotificationCompat.Builder(this)
.setContentTitle(String.valueOf(i))
.setContentText(String.valueOf(i))
.setSmallIcon(R.drawable.musicplayer)
.setContentIntent(pIntent)
.setAutoCancel(true).build();
;
startForeground(101, notification);
}
public class MyLocalBinder extends Binder {
ServiceDemo getService() {
return ServiceDemo.this;
}
}
private final IBinder myBinder = new MyLocalBinder();
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return myBinder;
}
}
put this two lines in manifest.
<service android:name=".ServiceDemo"
android:enabled="true"/>
You need to stop the player in onPause(). Following code can be used:
#Override
protected void onPause() {
super.onPause();
if (this.isFinishing()){
player.stop();
}
}
Check Android Stop Background Music for more details
for that you should stop the service in the onCreate method of the Activity. Below is the code for it :
stopService(new Intent(MyService.MY_SERVICE));
Best of Luck!
In Your MainActivity , You Should Call stopService() Inside MainActivity
#Override
public void OnPause() {
stopService(svc);
}