I am new to android development , my app is ready but on some devices it lags when opening the navigation drawer and somethings on onclick event.I tried to use threads so that each event occurs on new thread but still i see lag please help me with this.
public class MainActivity extends BaseActivity implements OnClickListener {
private Button scanBtn,scanBtn2,scanBtn3;
Animation animTranslate,animAlpha;
LinearLayout lv;
Handler handler;
String[] permissions;
#Override
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.activity_base);
super.onCreate(savedInstanceState);
permissions = new String[3];
permissions[0] = Manifest.permission.WRITE_EXTERNAL_STORAGE;
permissions[1] = Manifest.permission.READ_EXTERNAL_STORAGE;
permissions[2]=Manifest.permission.CAMERA;
ActivityCompat.requestPermissions(
this,
permissions,
5
);
scanBtn = (Button)findViewById(R.id.scanner);
scanBtn2=(Button)findViewById(R.id.scanner2);
scanBtn3=(Button)findViewById(R.id.scanner3);
lv=(LinearLayout)findViewById(R.id.container);
animTranslate= AnimationUtils.loadAnimation(MainActivity.this,R.anim.anim_translate);
animAlpha=AnimationUtils.loadAnimation(MainActivity.this,R.anim.anim_alpha);
scanBtn.setOnClickListener(MainActivity.this);
scanBtn2.setOnClickListener(MainActivity.this);
scanBtn3.setOnClickListener(MainActivity.this);
}
public void onClick(View v){
if(v.getId()==R.id.scanner){
v.startAnimation(animTranslate);
lv.startAnimation(animAlpha);
final IntentIntegrator scanIntegrator = new IntentIntegrator(this);
scanIntegrator.setDesiredBarcodeFormats(IntentIntegrator.QR_CODE_TYPES);
scanIntegrator.setPrompt(" ");
scanIntegrator.setCameraId(0);
scanIntegrator.setBeepEnabled(true);
scanIntegrator.setBarcodeImageEnabled(false);
handler=new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
scanIntegrator.initiateScan();
}
},500);
}else if(v.getId()==R.id.scanner2){
v.startAnimation(animTranslate);
lv.startAnimation(animAlpha);
final IntentIntegrator scanIntegrator2=new IntentIntegrator(this);
scanIntegrator2.setDesiredBarcodeFormats(IntentIntegrator.ONE_D_CODE_TYPES);
scanIntegrator2.setPrompt(" ");
scanIntegrator2.setCameraId(0);
scanIntegrator2.setBeepEnabled(true);
scanIntegrator2.setBarcodeImageEnabled(true);
handler=new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
scanIntegrator2.initiateScan();
}
},500);
}else if(v.getId()==R.id.scanner3){
v.startAnimation(animTranslate);
lv.startAnimation(animAlpha);
final Intent intent=new Intent(this,GenerateQRCodeActivity.class);
handler=new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
startActivity(intent); overridePendingTransition(R.anim.slide_in_right,R.anim.slide_out_left);
}
},500);
}
}
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
IntentResult scanningResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
if (scanningResult != null) {
String scanContent = scanningResult.getContents();
String scanFormat = scanningResult.getFormatName();
Intent intent1=new Intent(this,ResultActivity.class);
intent1.putExtra("con",scanContent);
if(scanContent != null && scanFormat != null) {
startActivity(intent1);
}
}
else{
Toast toast = Toast.makeText(getApplicationContext(),
"No scan data received!", Toast.LENGTH_SHORT);
toast.show();
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent e) {
if (keyCode == KeyEvent.KEYCODE_MENU) {
// your action...
if (!mDrawerLayout.isDrawerOpen(mDrawerList)) {
mDrawerLayout.openDrawer(mDrawerList);
}
else{
mDrawerLayout.closeDrawer(mDrawerList);
}
return true;
}
return super.onKeyDown(keyCode, e);
}
#Override
public void onBackPressed() {
if(mDrawerLayout.isDrawerOpen(mDrawerList)){
mDrawerLayout.closeDrawer(mDrawerList);
}
else{
finish();
}
}
}
Related
If there is no Internet, display a certain xml in full screen when the application starts, that there is no Internet, and if there is, perform MainActivity.
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener, MaterialSearchBar.OnSearchActionListener, PopupMenu.OnMenuItemClickListener {
private static final String TAG = "MainActivity";
#SuppressLint("StaticFieldLeak")
public static MaterialSearchBar searchBar;
private DrawerLayout drawer;
private NavigationView navigationView;
private AdView mAdView;
private static List<String> listPermissionsNeeded;
public boolean isInternetAvailable() {
try {
InetAddress address = InetAddress.getByName("www.google.com");
return !address.equals("");
} catch (UnknownHostException e) {
// Log error
}
return false;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
Log.d(TAG, "onCreate: setting things up");
StaticUtils.requestQueue = (RequestQueue) Volley.newRequestQueue(getApplicationContext());
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Admob banner
MobileAds.initialize(this, new OnInitializationCompleteListener() {
#Override
public void onInitializationComplete(InitializationStatus initializationStatus) {
}
});
mAdView = findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
mAdView.setAdListener(new AdListener() {
#Override
public void onAdLoaded() {
super.onAdLoaded();
mAdView.setVisibility(View.VISIBLE);
}
#Override
public void onAdFailedToLoad(int i) {
super.onAdFailedToLoad(i);
mAdView.setVisibility(View.GONE);
}
});
//restoring recent searches list
StaticUtils.recentSearchesList = getArrayList(StaticUtils.KEY_LIST_PREFERENCCES);
if (StaticUtils.recentSearchesList==null){
StaticUtils.recentSearchesList = new ArrayList<>();
}
StaticUtils.savedImagesList = new ArrayList<>();
searchBar = findViewById(R.id.searchToolBar);
searchBar.setHint("Search Wallpapers");
searchBar.setOnSearchActionListener(this);
searchBar.hideSuggestionsList();
drawer = findViewById(R.id.drawer_layout);
navigationView = findViewById(R.id.nav_view);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
navigationView.setNavigationItemSelectedListener(this);
//sets home fragment open by default
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new HomeFragment()).commit();
playLogoAudio(); //to play the logo audio
searchEvents(); //advanced search events
}
#Override
public void onBackPressed() {
Log.d(TAG, "onBackPressed: back button invoked.");
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
public void grantPermissionBottomSheet(){
View dialogView = getLayoutInflater().inflate(R.layout.layout_bottomsheet, null);
final BottomSheetDialog dialog = new BottomSheetDialog(this);
Button ok = dialogView.findViewById(R.id.bt_bottomsheet);
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: bottomSheet button clicked.");
requestPermissions(MainActivity.this);
dialog.dismiss();
}
});
dialog.setContentView(dialogView);
dialog.show();
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Log.d(TAG, "onNavigationItemSelected: navigation item pressed.");
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_home) {
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new HomeFragment()).commit();
} else if (id == R.id.nav_saved) {
NetworkUtils network = new NetworkUtils(this);
if(network.checkConnection(drawer)){ //if network connected
Intent i = new Intent(MainActivity.this, SecondActivity.class);
i.putExtra(StaticUtils.KEY_FRAG_ID,2);
i.putExtra(StaticUtils.KEY_SEARCH_DATA,"Saved");
startActivity(i);
}
}else if (id == R.id.nav_downloads) {
//downloaded images
if (permissionsGranted(this)) {
Intent i = new Intent(MainActivity.this, SecondActivity.class);
i.putExtra(StaticUtils.KEY_FRAG_ID, 4); //4 for downloads section
i.putExtra(StaticUtils.KEY_SEARCH_DATA, "Downloads");
startActivity(i);
}else{
grantPermissionBottomSheet();
}
} else if (id == R.id.nav_share) {
//share the app intent
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, "Hey! look what I found from play store.\nDownload cool & amazing wallpapers for your device from this app, "+getResources().getString(R.string.app_name)+", among various categories.\n\nCheck this out:\n"+StaticUtils.playStoreUrlDefault+getPackageName()+"\nDownload now:)");
sendIntent.setType("text/plain");
startActivity(Intent.createChooser(sendIntent, "Share app through..."));
} else if (id == R.id.nav_rate) {
//rate the app intent
Uri uri = Uri.parse("market://details?id=" + getApplicationContext().getPackageName());
Intent goToMarket = new Intent(Intent.ACTION_VIEW, uri);
// To count with Play market backstack, After pressing back button,
// to taken back to our application, we need to add following flags to intent.
goToMarket.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY |
Intent.FLAG_ACTIVITY_NEW_DOCUMENT |
Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
try {
startActivity(goToMarket);
} catch (Exception e) {
startActivity(new Intent(Intent.ACTION_VIEW,
Uri.parse("http://play.google.com/store/apps/details?id=" + getApplicationContext().getPackageName())));
}
} else if (id == R.id.nav_about) {
//about page
Intent i = new Intent(MainActivity.this, SecondActivity.class);
i.putExtra(StaticUtils.KEY_FRAG_ID,3); //3 for about fragment
i.putExtra(StaticUtils.KEY_SEARCH_DATA,"About");
startActivity(i);
}
drawer.closeDrawer(GravityCompat.START);
return true;
}
public void playLogoAudio(){
Log.d(TAG, "playLogoAudio: playing logo audio");
View headerView = navigationView.getHeaderView(0);
ImageView drawerLogo = headerView.findViewById(R.id.imageLogo);
drawerLogo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MediaPlayer mediaPlayer = MediaPlayer.create(MainActivity.this,R.raw.hello);
mediaPlayer.start();
}
});
}
#Override
public boolean onMenuItemClick(MenuItem item) {
return false;
}
#Override
public void onSearchStateChanged(boolean enabled) {
if (enabled){
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new SearchFragment()).commit();
}else{
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new HomeFragment()).commit();
}
}
#Override
public void onSearchConfirmed(CharSequence text) {
Log.d(TAG, "onSearchConfirmed: confirmed search: "+text);
Intent i = new Intent(this,SecondActivity.class);
i.putExtra(StaticUtils.KEY_FRAG_ID,1);
i.putExtra(StaticUtils.KEY_SEARCH_DATA,String.valueOf(text));
if(new NetworkUtils(getApplicationContext()).checkConnection(drawer)) { //start intent if network connected
StaticUtils.recentSearchesList.add(String.valueOf(text)); //adds the query to the recents list
if (StaticUtils.recentSearchesList.size()>20){
StaticUtils.recentSearchesList.remove(0);
}
SearchFragment.updateAdapter(this,StaticUtils.recentSearchesList);
searchBar.setText(""); //removes the search query
startActivity(i);
}
}
#Override
public void onButtonClicked(int buttonCode) {
Log.d(TAG, "onButtonClicked: search interface button clicked: "+buttonCode);
switch (buttonCode){
case MaterialSearchBar.BUTTON_NAVIGATION:
drawer.openDrawer(GravityCompat.START);
break;
case MaterialSearchBar.BUTTON_BACK:
searchBar.disableSearch();
}
}
#Override
public void onPointerCaptureChanged(boolean hasCapture) {}
public void saveArrayList(ArrayList<String> list, String key){
Log.d(TAG, "saveArrayList: saving recent searchList data");
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = prefs.edit();
Gson gson = new Gson();
String json = gson.toJson(list);
editor.putString(key, json);
editor.apply();
}
public ArrayList<String> getArrayList(String key){
Log.d(TAG, "getArrayList: getting saved recent searchList data");
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
Gson gson = new Gson();
String json = prefs.getString(key, null);
Type type = new TypeToken<ArrayList<String>>() {}.getType();
return gson.fromJson(json, type);
}
#Override
protected void onPause() {
super.onPause();
//Saving arraylist when activity gets paused
saveArrayList(StaticUtils.recentSearchesList,StaticUtils.KEY_LIST_PREFERENCCES);
}
public void searchEvents(){
Log.d(TAG, "searchEvents: managing the search events");
searchBar.addTextChangeListener(new TextWatcher() {
ArrayList<String> tempList = new ArrayList<>();
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
Log.d(TAG, "beforeTextChanged: clearing the list");
if (!tempList.isEmpty()){
tempList.clear();
}
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
Log.d(TAG, "onTextChanged: changing search query");
for (String string : StaticUtils.recentSearchesList) {
if (s.length() > 0) {
if (string.matches("(?i)(" + s + ").*")) {
tempList.add(string);
SearchFragment.updateAdapter(getApplicationContext(), tempList);
}
}else{
SearchFragment.updateAdapter(getApplicationContext(), StaticUtils.recentSearchesList);
}
}
}
#Override
public void afterTextChanged(Editable s) {}
});
}
#Override
protected void onResume() {
super.onResume();
navigationView.setCheckedItem(R.id.nav_home);
if (!permissionsGranted(this)){ //checking and requesting permissions
grantPermissionBottomSheet();
}
}
public static boolean permissionsGranted(Context context) {
Log.d(TAG, "checkPermissions: checking if permissions granted.");
int result;
listPermissionsNeeded = new ArrayList<>();
for (String p:permissions) {
result = ContextCompat.checkSelfPermission(context,p);
if (result != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(p);
}
}
//if all/some permissions not granted
return listPermissionsNeeded.isEmpty();
}
public static void requestPermissions(Activity activity){
Log.d(TAG, "requestPermissions: requesting permissions.");
ActivityCompat.requestPermissions(activity, listPermissionsNeeded.toArray(new
String[listPermissionsNeeded.size()]), StaticUtils.MULTIPLE_PERMISSIONS);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
Log.d(TAG, "onRequestPermissionsResult: action when permission granted or denied");
if (requestCode == StaticUtils.MULTIPLE_PERMISSIONS) {
if (grantResults.length <= 0) {
// no permissions granted.
showPermissionDialog();
}
}
}
public void showPermissionDialog(){
Log.d(TAG, "showPermissionDialog: requesting permissions");
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Are you sure?");
builder.setMessage("You'll not be able to use this app properly without these permissions.");
builder.setPositiveButton("Try Again", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//re-requesting permissions
requestPermissions(MainActivity.this);
}
});
builder.setNegativeButton("Cancel", null);
builder.show();
}
}
I would suggest some kind of different flow.
Most apps have something called a "Splash screen" (usually with a logo, sometimes kind of a progress bar).
what you can do is create a splash activity, - if there is internet call your MainActiviy, otherwise call another activity NetworkErrorActivity with the XML you want.
Hi in the below code displaying the devices near by via bluetooth.
The below code was working fine for every device except one plus 6 phone.
I found a bug in the one plus 6 phone. If we turn on bluetooth and location then list of the near devices are listed.
can any one help me how to reslove the bug especially on one plus phones.
public class DeviceScanActivity extends AppCompatActivity {
private static final String TAG = DeviceScanActivity.class.getSimpleName();
private static final int PERMISSION_REQUEST_COARSE_LOCATION = 1;
#Bind(R.id.back)
TextView mBack;
#Bind(R.id.refresh)
TextView mRefresh;
#Bind(R.id.toolBar)
Toolbar mToolBar;
#Bind(R.id.scan_status)
TextView mScanStatus;
#Bind(R.id.deviceListView)
RecyclerView mDeviceListView;
#Bind(R.id.scanningProgress)
ProgressBar mScanningProgress;
private DeviceListAdapter mAdapter;
private BleService mBleService;
private List<BluetoothDevice> mBleDevices;
private SharedPreferences mPref;
private ProgressDialog mProgressDialog;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scan_device);
ButterKnife.bind(this);
mProgressDialog = new ProgressDialog(this);
mPref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
initToolBar();
mBleDevices = new ArrayList<>();
mAdapter = new DeviceListAdapter(this);
mDeviceListView.setAdapter(mAdapter);
LinearLayoutManager manager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
mDeviceListView.setLayoutManager(manager);
mDeviceListView.addOnItemTouchListener(new RecyclerItemClickListener(this, new RecyclerItemClickListener.OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
showProgressDialog();
List<BluetoothDevice> bluetoothDevices = mAdapter.getBluetoothDevices();
if (bluetoothDevices != null) {
if (bluetoothDevices.size() > position) {
BluetoothDevice bluetoothDevice = bluetoothDevices.get(position);
if (bluetoothDevice != null) {
String address = bluetoothDevice.getAddress();
mBleService.connect(address);
}
}
}
}
}));
final IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(BleService.ACTION_DEVICE_FOUND);
intentFilter.addAction(BleService.ACTION_GATT_CONNECTED);
intentFilter.addAction(BleService.ACTION_GAT_CONNECTING);
intentFilter.addAction(BleService.ACTION_GATT_DISCONNECTED);
intentFilter.addAction(BleService.ACTION_GAT_SERVICE_DISCOVERED);
registerReceiver(mGattUpdateReceiver, intentFilter);
if (ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.BLUETOOTH,Manifest.permission.ACCESS_FINE_LOCATION
, Manifest.permission.BLUETOOTH_ADMIN, Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSION_REQUEST_COARSE_LOCATION);
}
} else {
if (mServiceConnection != null) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, 101);
}
Intent intent = new Intent(this, BleService.class);
bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE);
}
}
private void showProgressDialog() {
if (mProgressDialog == null) {
mProgressDialog = new ProgressDialog(this);
}
mProgressDialog.setMessage(getString(R.string.loading));
mProgressDialog.setCanceledOnTouchOutside(false);
mProgressDialog.show();
}
private ServiceConnection mServiceConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
mBleService = ((BleService.LocalBinder) iBinder).getLeService();
if (mBleService != null) {
mBleService.scanLeDevice(true);
mScanStatus.setVisibility(View.VISIBLE);
mScanStatus.setText(R.string.scanning_device);
}
}
#Override
public void onServiceDisconnected(ComponentName componentName) {
}
};
#Override
protected void onResume() {
super.onResume();
}
#Override
protected void onStart() {
super.onStart();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 101) {
if (mBleService != null) {
mBleService.scanLeDevice(true);
}
}
}
private BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
switch (action) {
case BleService.ACTION_DEVICE_FOUND:
BluetoothDevice device = (BluetoothDevice) intent.getParcelableExtra(BleService.EXTRA_DEVICE);
if (mBleDevices != null) {
if (!mBleDevices.contains(device)) {
mBleDevices.add(device);
mAdapter.udpateBluetoothDevices(mBleDevices);
mAdapter.notifyDataSetChanged();
}
}
break;
case BleService.ACTION_GATT_CONNECTED:
Log.d(TAG, "!Action gat connected...");
mBleService.scanLeDevice(false);
mScanStatus.setVisibility(View.VISIBLE);
mScanStatus.setText(getString(R.string.connected));
break;
case BleService.ACTION_GAT_CONNECTING:
mScanStatus.setVisibility(View.VISIBLE);
mScanStatus.setText(getString(R.string.connecting));
Log.d(TAG, "!Action Gat Connecting..");
break;
case BleService.ACTION_GATT_DISCONNECTED:
mScanStatus.setVisibility(View.VISIBLE);
mScanStatus.setText(getString(R.string.disconnected));
mScanningProgress.setVisibility(View.GONE);
mRefresh.setVisibility(View.VISIBLE);
if (mProgressDialog != null) {
mProgressDialog.dismiss();
}
Log.d(TAG, "!Action Gat Disconnected..");
break;
case BleService.ACTION_GAT_SERVICE_DISCOVERED:
boolean isOperator = mPref.getBoolean(Constants.IS_OPERATOR, false);
if (mProgressDialog != null) {
mProgressDialog.dismiss();
}
if (isOperator) {
Intent homeIntent = new Intent(DeviceScanActivity.this, HomeScreenActivity.class);
startActivity(homeIntent);
finish();
} else {
Intent lightControllIntent = new Intent(DeviceScanActivity.this, LightConfigurationActivity.class);
startActivity(lightControllIntent);
finish();
}
mScanStatus.setText(getString(R.string.discoveringService));
Log.d(TAG, "!Action Gat Discovering..");
break;
}
}
};
private void initToolBar() {
mRefresh.setVisibility(View.VISIBLE);
}
#OnClick(R.id.refresh)
public void onClick() {
mScanStatus.setVisibility(View.VISIBLE);
mRefresh.setVisibility(View.GONE);
mScanningProgress.setVisibility(View.VISIBLE);
mBleDevices.clear();
mAdapter.udpateBluetoothDevices(new ArrayList<BluetoothDevice>());
mAdapter.notifyDataSetChanged();
}
#Override
protected void onDestroy() {
if (mServiceConnection != null) {
unbindService(mServiceConnection);
}
if (mGattUpdateReceiver != null) {
unregisterReceiver(mGattUpdateReceiver);
}
super.onDestroy();
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if (requestCode == PERMISSION_REQUEST_COARSE_LOCATION) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (mServiceConnection != null) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, 101);
}
Intent intent = new Intent(this, BleService.class);
bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE);
} else {
finish();
}
}
}
}
I want to play 6 different sounds triggered by 6 different buttons in background, so that if the app is on background the sound keeps playing.
When one sound is already playing, pressing another button will stop it and play its own sound,
Tapping the same button 2K times it stops, 2K+1 times: starts again.. (K is a non-null integer)
All of the code is done and seems to be working correctly, except that the player stops after one and a half minute. (This is not because of low memory)
Can anyone please tell me what am I doing wrong?
public class PlayService extends Service {
private MediaPlayer player;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
player = new MediaPlayer();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
int btnId = intent.getExtras().getInt("ID");
Toast.makeText(this, "onStart service" + btnId, Toast.LENGTH_SHORT).show();
selectResId(btnId);
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service destroyed", Toast.LENGTH_SHORT).show();
if (player != null) {
player.stop();
player.release();
}
player = null;
}
#Override
public void onLowMemory() {
super.onLowMemory();
Toast.makeText(this, "Low mem", Toast.LENGTH_SHORT).show();
}
private void selectResId(int resId){
switch (resId){
case 1: playMediaFromResource(R.raw.number_one);
case 2: playMediaFromResource(R.raw.number_two);
case 3: playMediaFromResource(R.raw.number_three);
case 4: playMediaFromResource(R.raw.number_four);
case 5: playMediaFromResource(R.raw.number_five);
case 6: playMediaFromResource(R.raw.number_six);
default: break;
}
}
private void playMediaFromResource(int resId) {
Uri mediaPath = Uri.parse("android.resource://" + getPackageName() + "/" + resId);
try {
player.setDataSource(getApplicationContext(), mediaPath);
player.setLooping(true);
player.prepare();
player.start();
} catch (Exception e) {
e.printStackTrace();
}
}
}
And the MainActivity:
public class MainActivity extends AppCompatActivity {
private Button btnStart1;
private Button btnStart2;
private Button btnStart3;
private Button btnStart4;
private Button btnStart5;
private Button btnStart6;
private Intent intent;
private int previousID = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewsByIds();
setOnClickListeners();
}
private void findViewsByIds() {
btnStart1 = findViewById(R.id.btn_start_1);
btnStart2 = findViewById(R.id.btn_start_2);
btnStart3 = findViewById(R.id.btn_start_3);
btnStart4 = findViewById(R.id.btn_start_4);
btnStart5 = findViewById(R.id.btn_start_5);
btnStart6 = findViewById(R.id.btn_start_6);
}
private void setOnClickListeners() {
btnStart1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
checkIntentState(1);
}
});
btnStart2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
checkIntentState(2);
}
});
btnStart3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
checkIntentState(3);
}
});
btnStart4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
checkIntentState(4);
}
});
btnStart5.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
checkIntentState(5);
}
});
btnStart6.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
checkIntentState(6);
}
});
}
private void checkIntentState(int ID) {
if (intent == null) {
createNewIntent(ID);
} else {
stopService(intent);
intent = null;
if (ID != previousID) {
createNewIntent(ID);
}
}
}
private void createNewIntent(int ID) {
intent = new Intent(MainActivity.this, PlayService.class);
intent.putExtra("ID", ID);
startService(intent);
previousID = ID;
}
}
I want to answer to my own question just in case anyone else runs into the problem.
It turns out, that Android added some new features (restricted access to background resources for battery life improvement purposes since Oreo(i.e. Android 8.0+ || API level 26)).
As the documentation says:
"Apps that are running in the background now have limits on how freely they can access background services."
So, in this case we will need to use foreground services.
mTabHost = getTabHost();
mTabHost.addTab(mTabHost.newTabSpec(TAB_NEWS).setIndicator(TAB_NEWS).setContent(new Intent(this, NewsActivity1.class)));
mTabHost.addTab(mTabHost.newTabSpec(TAB_BBS).setIndicator(TAB_BBS).setContent(new Intent(this, BBSActivity.class)));
mTabHost.addTab(mTabHost.newTabSpec(TAB_CATEGORY).setIndicator(TAB_CATEGORY).setContent(new Intent(this, CategoryActivity.class)));
mTabHost.addTab(mTabHost.newTabSpec(TAB_DISCOVER).setIndicator(TAB_DISCOVER).setContent(new Intent(this, DiscoverActivity.class)));
mTabHost.addTab(mTabHost.newTabSpec(TAB_MINE).setIndicator(TAB_MINE).setContent(new Intent(this, MineActivity.class)));
Because a reason, i use the TabActivity, but the system's permission dialog can't show in targetSdk23.
for example: in NewsActivity, BBSActivity,CategoryActivity,DiscoverActivity,MineActivity, all cant show.
please help me, thanks~
for example DiscoverActivity:
public class DiscoverActivity extends BaseActivity implements View.OnClickListener{
private RelativeLayout near, plate, search, rate, oil, two_dimension_code, rl_activity, coupon;
private TextView tvActivityTitle;
private String url;
private LoadDialog dialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_discover);
GoogleAnalyticsUtil.doGoogleAnalytics();
initView();
initEvent();
}
private void initView() {
// TODO Auto-generated method stub
near = (RelativeLayout) findViewById(R.id.discover_near);
plate = (RelativeLayout) findViewById(R.id.discover_plate);
search = (RelativeLayout) findViewById(R.id.discover_search);
rate = (RelativeLayout) findViewById(R.id.discover_rate);
oil = (RelativeLayout) findViewById(R.id.discover_oil);
two_dimension_code = (RelativeLayout) findViewById(R.id.rl_twodimension_code);
rl_activity = (RelativeLayout) findViewById(R.id.rl_activity);
coupon = (RelativeLayout) findViewById(R.id.rl_coupon);
tvActivityTitle = (TextView) findViewById(R.id.tv_activity_title);
}
private void initEvent() {
near.setOnClickListener(this);
plate.setOnClickListener(this);
search.setOnClickListener(this);
rate.setOnClickListener(this);
oil.setOnClickListener(this);
two_dimension_code.setOnClickListener(this);
rl_activity.setOnClickListener(this);
coupon.setOnClickListener(this);
}
#Override
public void onClick(View v) {
final Intent intent = new Intent();
switch (v.getId()) {
case R.id.discover_near:
GoogleAnalyticsUtil.doGoogleActionAnalytics(GoogleAnalyticsConstant.ActionEvent.NEARPEOPLE_ACTION);
if (TextUtils.isEmpty(ShareProUtils.getUid(this))) {
intent.setClass(this, LoginActivity.class);
startActivity(intent);
} else {
intent.setClass(this, NearbyActivity.class);
startActivity(intent);
}
break;
case R.id.discover_plate:
intent.setClass(this, ForumActivity.class);
startActivity(intent);
break;
case R.id.discover_search:
intent.setClass(this, TopicSearchActivity.class);
startActivity(intent);
break;
case R.id.discover_rate:
intent.setClass(this, RateActivity.class);
startActivity(intent);
break;
case R.id.discover_oil:
intent.setClass(this, OilActivity.class);
startActivity(intent);
break;
case R.id.rl_twodimension_code:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
DialogUtil.getInstance().showPermissionDialog(this, "permission");
} else {
intent.setClass(DiscoverActivity.this, CaptureActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivityForResult(intent, 1);
}
} else {
intent.setClass(DiscoverActivity.this, CaptureActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivityForResult(intent, 1);
}
break;
case R.id.rl_activity:
intent.setClass(this, WebViewActivity.class);
intent.putExtra("url", url);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
break;
case R.id.rl_coupon:
intent.setClass(this, GroupBuyListActivity.class);
startActivity(intent);
break;
}
}
private void loadActivity() {
Map<String, String> mp = new HashMap<String, String>();
Okhttp.getIntance().post(Api.REAL_URL, Api.YORKBBS_CMS_TXTSETTING, mp, new StringCallback() {
#Override
public void onError(Call call, Exception e) {
}
#Override
public void onResponse(String response) {
if (!TextUtils.isEmpty(response)) {
String result = ParamUtils.ConvertData(response);
JsonObject jsonObject = new JsonParser().parse(result).getAsJsonObject();
if (jsonObject.has("list")) {
rl_activity.setVisibility(View.VISIBLE);
String list = jsonObject.get("list").toString();
List<Discoverac> listObj = new Gson().fromJson(list, new TypeToken<List<Discoverac>>() {
}.getType());
if (listObj != null && listObj.size() > 0) {
tvActivityTitle.setText(listObj.get(0).getTxt());
url = listObj.get(0).getUrl();
}
}
}
rl_activity.setVisibility(View.GONE);
}
});
}
private void check(String ticket) {
Map<String, String> mp = new HashMap<String, String>();
mp.put("sessionkey", ShareProUtils.getLoginSession(this));
mp.put("code", ticket);
mp.put("merchantid", ShareProUtils.getUid(this));
Okhttp.getIntance().post(Api.GROUPBUY_URL, Api.GROUPON_CHECK, mp, new StringCallback() {
#Override
public void onBefore(Request request) {
super.onBefore(request);
dialog = DialogUtil.getInstance().showLoadDialog(DiscoverActivity.this, "正在验证...");
}
#Override
public void onError(Call call, Exception e) {
}
#Override
public void onResponse(String response) {
if (!TextUtils.isEmpty(response)) {
String result = ParamUtils.ConvertData(response);
GrouponDetailResponse response1 = new Gson().fromJson(result,GrouponDetailResponse.class);
if (response1.getFlag().equals("0")){
Intent intent = new Intent(DiscoverActivity.this, TicketCheckSuccessActivity.class);
startActivity(intent);
}else {
Intent intent = new Intent(DiscoverActivity.this, TicketCheckFailActivity.class);
startActivity(intent);
}
} else {
TipsToast.show(DiscoverActivity.this, "error");
}
}
#Override
public void onAfter() {
DialogUtil.getInstance().dissMissDialog(dialog);
super.onAfter();
}
});
}
#Override
protected void onResume() {
super.onResume();
if (isNet()) {
loadActivity();
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
if (requestCode == 1) {
Bundle bundle = data.getExtras();
String result = bundle.getString("result");
if (!TextUtils.isEmpty(result)) {
if (result.contains("code")) {
if (TextUtils.isEmpty(ShareProUtils.getUid(this))) {
Intent login = new Intent(this, LoginActivity.class);
startActivity(login);
return;
}
result = result.replaceAll("http://www.yorkbbs.ca\\?yorkbbscode=","");
check(result);
} else {
Intent intent = new Intent(this, WebViewActivity.class);
intent.putExtra("url", result);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
} else {
TipsToast.show(this, "scan error");
}
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
// NOTE: delegate the permission handling to generated method
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
return false;
}
}
TabActivity is now deprecated. To Create Tab you have to create it using Fragment and ViewPager.
Here is example to create Tab using Fragment and ViewPager .
see Exmaple here : http://www.truiton.com/2015/06/android-tabs-example-fragments-viewpager/
My code is as follows
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
runBtn = (Button)findViewById(R.id.button_run_demo);
ttobj = new TextToSpeech(getApplicationContext(),
new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if (status != TextToSpeech.ERROR) {
ttobj.setLanguage(Locale.UK);
}
}
});
runBtn.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v) {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);
}
});
}
public void onPause() {
if (ttobj != null) {
ttobj.stop();
ttobj.shutdown();
}
super.onPause();
}
public void speakText(String text) {
String toSpeak = text;
Toast.makeText(getApplicationContext(), toSpeak,
Toast.LENGTH_SHORT).show();
ttobj.speak(toSpeak, TextToSpeech.QUEUE_FLUSH, null);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_PIC_REQUEST) {
//do my stuff
speakText("Hello");
}
}
Although I am able to do my stuff I am not able to run speech.
Am I missing something ??
Thanks All
When onActivityResult() is called the TextToSpeech is already shutdown since you shut it down in onPause(). You have to either set a flag to speak "Hello" when TextToSpeech is reinitialize or put your code in onPause() in onDestroy().