I am trying to Discover two devices each other using WifiDirect. Devices are running Android version 8.0 and 9.0 respectively. But not able to succeed.
First time I click on Discover button on both devices both waits for 2-3 seconds and shows No device found Toast.
Second time I try to discover on both within a second both show up the No device found Toast.
MainActivity.java
package com.example.prototypewfp2p;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.net.wifi.WifiManager;
import android.net.wifi.p2p.WifiP2pDevice;
import android.net.wifi.p2p.WifiP2pDeviceList;
import android.net.wifi.p2p.WifiP2pManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.security.Permission;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
Button btnOnOff, btnDiscover, btnSend;
ListView listView;
TextView read_msg_box, ConnectoinStatus;
EditText writeMsg;
WifiManager wifiManager;
WifiP2pManager mMangaer;
WifiP2pManager.Channel mChannel;
BroadcastReceiver mReceiver;
IntentFilter mIntentFilter;
List<WifiP2pDevice> peers = new ArrayList<WifiP2pDevice>();
String[] deviceNameArray;
WifiP2pDevice[] deviceArray;
// Permissions Related
public String[] PermissionsList = {Manifest.permission.CHANGE_WIFI_STATE, Manifest.permission.ACCESS_WIFI_STATE, Manifest.permission.INTERNET, Manifest.permission.ACCESS_NETWORK_STATE
, Manifest.permission.CHANGE_NETWORK_STATE, Manifest.permission.ACCESS_FINE_LOCATION};
public int permsRequestCode = 200;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Permissions
for (int i = 0; i < PermissionsList.length; i++) {
if (ContextCompat.checkSelfPermission(MainActivity.this, PermissionsList[i]) == PackageManager.PERMISSION_DENIED) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(PermissionsList, permsRequestCode);
}
} else {
Toast.makeText(MainActivity.this, "Permissions Granted Already!", Toast.LENGTH_SHORT).show();
}
}
//Calling Functions Declared below
initialWork();
exqListener();
}
//Permission (Override stuff)
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (permsRequestCode) {
case 200:
if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
Toast.makeText(this,"Permission[1] granted!",Toast.LENGTH_LONG);
}
else{Toast.makeText(this,"Permission[1] Denied!",Toast.LENGTH_LONG);}
if(grantResults.length > 0 && grantResults[2] == PackageManager.PERMISSION_GRANTED){Log.i("myTag","Permission 3 granted");}
if(grantResults.length > 0 && grantResults[3] == PackageManager.PERMISSION_GRANTED){Log.i("myTag","Permission 4 granted");}
if(grantResults.length > 0 && grantResults[4] == PackageManager.PERMISSION_GRANTED){Log.i("myTag","Permission 5 granted");}
if(grantResults.length > 0 && grantResults[5] == PackageManager.PERMISSION_GRANTED){Log.i("myTag","Permission 6 granted");}
if(grantResults.length > 0 && grantResults[1] == PackageManager.PERMISSION_GRANTED){Log.i("myTag","Permission 2 granted");}
// boolean first = grantResults[0] == PackageManager.PERMISSION_GRANTED;
// boolean second = grantResults[1] == PackageManager.PERMISSION_GRANTED;
// boolean third = grantResults[2] == PackageManager.PERMISSION_GRANTED;
// boolean fourth = grantResults[3] == PackageManager.PERMISSION_GRANTED;
// boolean fifth = grantResults[4] == PackageManager.PERMISSION_GRANTED;
// boolean sixth = grantResults[5] == PackageManager.PERMISSION_GRANTED;
break;
}
}
private void exqListener() {
btnOnOff.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (wifiManager.isWifiEnabled()) {
wifiManager.setWifiEnabled(false);
// Toast.makeText(MainActivity.this,"Wifi is turned OFF",Toast.LENGTH_LONG).show();
} else {
wifiManager.setWifiEnabled(true);
// Toast.makeText(MainActivity.this,"Wifi is turned ON",Toast.LENGTH_LONG).show();
}
}
});
btnDiscover.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION},1);
}
return;
}
mMangaer.discoverPeers(mChannel, new WifiP2pManager.ActionListener() {
#Override
public void onSuccess() {
ConnectoinStatus.setText("Discovery Started!");
}
#Override
public void onFailure(int reason) {
ConnectoinStatus.setText("Could not start Discovery");
}
});
}
});
}
private void initialWork() {
btnOnOff = (Button) findViewById(R.id.onOff);
btnDiscover = (Button) findViewById(R.id.discover);
btnSend = (Button) findViewById(R.id.sendButton);
listView = (ListView) findViewById(R.id.peerListView);
read_msg_box = (TextView) findViewById(R.id.readMsg);
ConnectoinStatus = (TextView) findViewById(R.id.connectionStatus);
writeMsg = (EditText) findViewById(R.id.writeMsg);
wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
mMangaer = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);
mChannel = mMangaer.initialize(this, getMainLooper(),null);
mReceiver = new WiFiDirectBroadcastReciever(mMangaer,mChannel,this);
mIntentFilter = new IntentFilter();
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);
}
WifiP2pManager.PeerListListener peerListListener = new WifiP2pManager.PeerListListener() {
#Override
public void onPeersAvailable(WifiP2pDeviceList peerList) {
if(!peerList.getDeviceList().equals(peers) ){
peers.clear();
peers.addAll(peerList.getDeviceList());
deviceNameArray = new String[peerList.getDeviceList().size()]; //Size of deviceNameArray initialized
deviceArray = new WifiP2pDevice[peerList.getDeviceList().size()]; //Size of deviceArray initialized
int index = 0;
//assigning device name and device to 'deviceNameArray' and 'deviceArray'
for (WifiP2pDevice device: peerList.getDeviceList()){
deviceNameArray[index] = device.deviceName;
deviceArray[index] = device;
index++;
}
ArrayAdapter<String> adapter= new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1,deviceNameArray);
listView.setAdapter(adapter);
}
if(peers.size()==0){
Toast.makeText(MainActivity.this,"No Device Found!",Toast.LENGTH_LONG).show();
return;
}
}
};
#Override
protected void onResume() {
super.onResume();
registerReceiver(mReceiver,mIntentFilter);
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(mReceiver);
}
}
WiFiDirectBroadcastReciever.java
package com.example.prototypewfp2p;
import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.wifi.WifiManager;
import android.net.wifi.p2p.WifiP2pManager;
import android.widget.Toast;
import androidx.core.app.ActivityCompat;
import static android.media.audiofx.Visualizer.STATE_ENABLED;
public class WiFiDirectBroadcastReciever extends BroadcastReceiver {
private WifiP2pManager mMangaer;
private WifiP2pManager.Channel mChannel;
private MainActivity mActivity;
public WiFiDirectBroadcastReciever(WifiP2pManager mMangaer, WifiP2pManager.Channel mChannel, MainActivity mActivity) {
this.mMangaer = mMangaer;
this.mActivity = mActivity;
this.mChannel = mChannel;
}
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION.equals(action)) {
int state = intent.getIntExtra(WifiP2pManager.EXTRA_WIFI_STATE, -1);
if (state == WifiP2pManager.WIFI_P2P_STATE_ENABLED) {
Toast.makeText(context, "Wifi is On", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, "Wifi is Off", Toast.LENGTH_SHORT).show();
}
} else if (WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION.equals(action)) {
if (mMangaer != null) {
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
Toast.makeText(context,"Acces Location (BroadcastRec) Not granted",Toast.LENGTH_SHORT).show();
}
mMangaer.requestPeers(mChannel, mActivity.peerListListener);
}
}
else if(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION.equals(action)){
}
else if(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION.equals(action)){
}
}
}
activitymain.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="#+id/onOff"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginStart="24dp"
android:layout_marginTop="47dp"
android:text="Wifi On/Off"
android:textSize="13dp" />
<Button
android:id="#+id/discover"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/onOff"
android:layout_alignBottom="#+id/onOff"
android:layout_centerHorizontal="true"
android:layout_marginBottom="3dp"
android:layout_marginLeft="0dp"
android:text="discover" />
<ListView
android:id="#+id/peerListView"
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout_alignParentStart="true"
android:layout_below="#+id/onOff"
android:layout_marginTop="25dp"
android:background="#android:color/holo_orange_light" />
<TextView
android:id="#+id/readMsg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentStart="true"
android:layout_below="#+id/peerListView"
android:layout_marginTop="31dp"
android:text="Message"
android:textAlignment="center"
android:textSize="20sp"
android:textStyle="italic" />
<EditText
android:id="#+id/writeMsg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentStart="true"
android:ems="10"
android:inputType="textPersonName"
android:layout_toStartOf="#+id/sendButton" />
<Button
android:id="#+id/sendButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:text="Send" />
<TextView
android:id="#+id/connectionStatus"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginTop="15dp"
android:text="Connection Status"
android:textAlignment="center"
android:textColor="#android:color/holo_blue_dark"
android:textSize="18sp"
android:textStyle="italic" />
</RelativeLayout>
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.prototypewfp2p">
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/Theme.Prototypewfp2p">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
IDK why But you have to enable gps (Location) on both devices.
I have also tested with android version 8 device and android 10 device gps enabled Both are working perfectly fine.
Related
I'm creating a Wallpaper application. I'm done with the categories and wallpapers inside each category using Picasso. And now I tried to make a new activity to view and download any wallpaper using Picasso. But after coding, when I click on the wallpaper the new activity never opens. Also there is no relevant error showing on the LogCat. Please help!
Here is the Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="me.umarkhan.walldeck">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.SET_WALLPAPER"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/FullScreenTheme">
<activity android:name=".ViewWallpaper"></activity>
<activity android:name=".ListWallpaper" />
<activity
android:name=".HomeActivity"
android:label="#string/title_activity_home"
android:theme="#style/FullScreenTheme" />
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
XML Code:
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/rootLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/white"
tools:context="me.umarkhan.walldeck.ViewWallpaper">
<com.google.android.material.appbar.AppBarLayout
android:id="#+id/app_bar_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<com.google.android.material.appbar.CollapsingToolbarLayout
android:id="#+id/collapsing"
android:fitsSystemWindows="true"
app:layout_scrollFlags="scroll|exitUntilCollapsed"
app:contentScrim="?attr/colorPrimary"
app:expandedTitleTextAppearance="#android:color/transparent"
android:layout_width="match_parent"
android:layout_height="350dp">
<ImageView
android:id="#+id/imageThumb"
android:contentDescription="WallDeck Wallpaper"
android:scaleType="centerCrop"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"
app:layout_collapseMode="pin"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"></androidx.appcompat.widget.Toolbar>
</com.google.android.material.appbar.CollapsingToolbarLayout>
</com.google.android.material.appbar.AppBarLayout>
<androidx.core.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="590dp"
android:clipToPadding="false"
app:layout_behavior="com.google.android.material.appbar.AppBarLayout$ScrollingViewBehavior"
tools:layout_editor_absoluteY="352dp">
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="16dp"
app:cardElevation="10dp"
app:cardUseCompatPadding="true">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="12dp"
android:padding="12dp"
android:text="Wallpaper description"
android:textSize="20sp"/>
</LinearLayout>
</androidx.cardview.widget.CardView>
</androidx.core.widget.NestedScrollView>
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/fabWallpaper"
android:layout_marginRight="30dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_terrain_black_24dp"
android:elevation="6dp"
app:pressedTranslationZ="12dp"
app:layout_anchor="#id/app_bar_layout"
app:layout_anchorGravity="bottom|right|end"
android:backgroundTint="#android:color/white"/>
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/fabDownload"
android:layout_marginLeft="30dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_file_download_black_24dp"
android:elevation="6dp"
app:pressedTranslationZ="12dp"
app:layout_anchor="#id/app_bar_layout"
app:layout_anchorGravity="bottom|left|start"
android:backgroundTint="#android:color/white"/>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
SaveImageHelper Class
package me.umarkhan.walldeck.Helper;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.provider.MediaStore;
import android.widget.Toast;
import com.squareup.picasso.Picasso;
import com.squareup.picasso.Target;
import java.lang.ref.WeakReference;
public class SaveImageHelper implements Target {
private Context context;
private WeakReference<AlertDialog> alertDialogWeakReference;
private WeakReference<ContentResolver> contentResolverWeakReference;
private String name;
private String desc;
public SaveImageHelper(Context context, AlertDialog alertDialog, ContentResolver contentResolver, String name, String desc) {
this.context = context;
this.alertDialogWeakReference =new WeakReference<AlertDialog>(alertDialog);
this.contentResolverWeakReference =new WeakReference<ContentResolver>(contentResolver);
this.name = name;
this.desc = desc;
}
#Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
ContentResolver r = contentResolverWeakReference.get();
AlertDialog alertDialog = alertDialogWeakReference.get();
if (r != null)
MediaStore.Images.Media.insertImage(r,bitmap,name,desc);
alertDialog.dismiss();
Toast.makeText(context,"Download Successful", Toast.LENGTH_SHORT).show();
//Open Gallery After Download
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
context.startActivity(Intent.createChooser(intent,"View Picture"));
}
#Override
public void onBitmapFailed(Drawable errorDrawable) {
}
#Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
}
ViewWallpaper Class
package me.umarkhan.walldeck;
import android.Manifest;
import android.app.AlertDialog;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import androidx.core.app.ActivityCompat;
import com.google.android.material.appbar.CollapsingToolbarLayout;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.squareup.picasso.Picasso;
import java.lang.annotation.Annotation;
import java.lang.annotation.ElementType;
import com.squareup.picasso.Target;
import java.util.UUID;
import dmax.dialog.SpotsDialog;
import me.umarkhan.walldeck.Common.Common;
import me.umarkhan.walldeck.Helper.SaveImageHelper;
public class ViewWallpaper extends AppCompatActivity {
CollapsingToolbarLayout collapsingToolbarLayout;
FloatingActionButton floatingActionButton,fabDownload;
ImageView imageView;
CoordinatorLayout rootLayout;
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode)
{
case Common.PERMISSION_REQUEST_CODE:
{
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
{
AlertDialog dialog = new SpotsDialog(ViewWallpaper.this);
dialog.show();
dialog.setMessage("Please Wait....");
String fileName = UUID.randomUUID().toString()+".png";
Picasso.with(getBaseContext())
.load(Common.select_background.getimageLink())
.into(new SaveImageHelper(getBaseContext(),
dialog,
getApplicationContext().getContentResolver(),
fileName,
"WallDeck Wallpapers"));
}
else
Toast.makeText(this,"You need to grant permission to download image", Toast.LENGTH_SHORT).show();
}
}
}
private Target target = new Target(){
#Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
}
#Override
public void onBitmapFailed(Drawable errorDrawable) {
}
#Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
};
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_wallpaper);
Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if (getSupportActionBar() != null)
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
//Init
rootLayout = (CoordinatorLayout)findViewById(R.id.rootLayout);
collapsingToolbarLayout = (CollapsingToolbarLayout)findViewById(R.id.collapsing);
collapsingToolbarLayout.setCollapsedTitleTextAppearance(R.style.CollapsedAppBar);
collapsingToolbarLayout.setExpandedTitleTextAppearance(R.style.ExpandedAppBar);
collapsingToolbarLayout.setTitle(Common.CATEGORY_SELECTED);
imageView = (ImageView)findViewById(R.id.imageThumb);
Picasso.with(this)
.load(Common.select_background.getimageLink())
.into(imageView);
floatingActionButton = (FloatingActionButton)findViewById(R.id.fabWallpaper);
floatingActionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Picasso.with(getBaseContext())
.load(Common.select_background.getimageLink())
.into(target);
}
});
fabDownload = (FloatingActionButton)findViewById(R.id.fabDownload);
fabDownload.setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
public void onClick(View view) {
//Check Permission
if (ActivityCompat.checkSelfPermission(ViewWallpaper.this,
Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)
{
requestPermissions(new String[]{ Manifest.permission.WRITE_EXTERNAL_STORAGE}, Common.PERMISSION_REQUEST_CODE);
return;
}
else
{
AlertDialog dialog = new SpotsDialog(ViewWallpaper.this);
dialog.show();
dialog.setMessage("Please Wait....");
String fileName = UUID.randomUUID().toString()+".png";
Picasso.with(getBaseContext())
.load(Common.select_background.getimageLink())
.into(new SaveImageHelper(getBaseContext(),
dialog,
getApplicationContext().getContentResolver(),
fileName,
"WallDeck Wallpapers"));
}
}
});
}
#Override
protected void onDestroy() {
Picasso.with(this).cancelRequest(target);
super.onDestroy();
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
if (item.getItemId() == android.R.id.home)
finish();
return super.onOptionsItemSelected(item);
}
}
I have already requested External Write Permission in HomeActivity:
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode)
{
case Common.PERMISSION_REQUEST_CODE:
{
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
Toast.makeText(this,"Permission Granted", Toast.LENGTH_SHORT).show();
else
Toast.makeText(this,"You need to grant permission to download image", Toast.LENGTH_SHORT).show();
}
break;
}
}
private AppBarConfiguration mAppBarConfiguration;
private Object Context;
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
Toolbar toolbar = findViewById(R.id.toolbar);
toolbar.setTitle("WallZone Pro");
setSupportActionBar(toolbar);
// Request Runtime Permission
if (ActivityCompat.checkSelfPermission(this,
Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)
{
requestPermissions(new String[]{ Manifest.permission.WRITE_EXTERNAL_STORAGE},Common.PERMISSION_REQUEST_CODE);
}
Please help!
Please add the class from which to go to ViewWallpaper.class
I am trying access the camera on an android device, so I tried some code from this site
I get this error: image at Imgur when I hover my mouse over 'file'. Take a look at the code below.
MainActivity.Java
package com.example.camera;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
public class MainActivity extends AppCompatActivity {
private Button takePictureButton;
private ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
takePictureButton = (Button) findViewById(R.id.button_image);
imageView = (ImageView) findViewById(R.id.imageView);
if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
takePictureButton.setEnabled(false);
ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE }, 0);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if (requestCode == 0) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED
&& grantResults[1] == PackageManager.PERMISSION_GRANTED){
takePictureButton.setEnabled(true);
}
}
}
public void takePicture(View view) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
file = Uri.fromFile(getOutputMediaFile());
intent.putExtra(MediaStore.EXTRA_OUTPUT, file);
startActivityForResult(intent, 100);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 100) {
if (resultCode == RESULT_OK) {
imageView.setImageURI(file);
}
}
}
private static File getOutputMediaFile(){
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "CameraDemo");
if (!mediaStorageDir.exists()){
if (!mediaStorageDir.mkdirs()){
return null;
}
}
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
return new File(mediaStorageDir.getPath() + File.separator +
"IMG_"+ timeStamp + ".jpg");
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<ImageView
android:id="#+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="#+id/button_image"
android:layout_width="wrap_content"
android:layout_height="48dp"
android:onClick="takePicture"
android:text="Take a picture!"/>
</RelativeLayout>
android_manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.camera">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Sorry if there are some formatting errors, I am quite new to Stack Overflow. The code is some testing for a future project. If anyone could answer my question on this error, +1 to you. I would really appreciate the help :)
You need to declare file variable globally.
Like:
private Uri file;
In Java
A variable is a container that holds values that are used in a
Java program. To be able to use a variable it needs to be declared.
Declaring variables is normally the first thing that happens in any
program.
My Android Phone model # is Sony Z3 Compact Japanese (SO-O2G)
Google Maps and all other apps related to location Works fine on my device
But i want to develop my own location-based application and on First step of developing my code is not working.. I don't know what is the problem in my Code. onLocationChange () method not triggered.. Even not finding my current location
Manifest Code
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.testingpurpose">
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-feature android:name="android.hardware.location.gps"/>
<uses-feature android:name="android.hardware.location.network"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
MainActivity.java
package com.testingpurpose;
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Handler;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private LocationManager locationManager;
private Location lastLocation;
private double distanceIntoMeters;
private final String PERMISSION_ONE = Manifest.permission.ACCESS_FINE_LOCATION;
private final String PERMISSION_TWO = Manifest.permission.ACCESS_COARSE_LOCATION;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (ContextCompat.checkSelfPermission(this,PERMISSION_ONE) != PackageManager.PERMISSION_GRANTED
&& ContextCompat.checkSelfPermission(this,PERMISSION_TWO ) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{PERMISSION_ONE, PERMISSION_TWO}, 0);
}
}
#Override
protected void onStart() {
super.onStart();
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if ( locationManager != null ){
if (ContextCompat.checkSelfPermission(this,PERMISSION_ONE) == PackageManager.PERMISSION_GRANTED
&& ContextCompat.checkSelfPermission(this,PERMISSION_TWO ) == PackageManager.PERMISSION_GRANTED) {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, listener);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, listener);
}
}
else{
Toast.makeText(this,"Permission not Granted",Toast.LENGTH_SHORT).show();
}
periodicallyCheck();
}
void periodicallyCheck(){
final Handler handler = new Handler();
final TextView tv = findViewById(R.id.tv);
handler.post(new Runnable() {
#Override
public void run() {
String format = String.format("%.2f %s",distanceIntoMeters,"meters");
tv.setText(format);
handler.postDelayed(this,1000);
}
});
}
private LocationListener listener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
if ( lastLocation == null ){
lastLocation = location;
}
Log.i("Location Updates: ",">>> Lat "+location.getLatitude()+" , >>> Long "+location.getLongitude());
distanceIntoMeters = distanceIntoMeters + location.distanceTo(lastLocation);
lastLocation = location;
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
};
#Override
protected void onDestroy() {
super.onDestroy();
if (locationManager != null && listener != null){
locationManager.removeUpdates(listener);
}
}
}
activityMain.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="#+id/tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#000"
android:textSize="50sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
I have an android app which is recording audio and outputting it withe the name audiorecorder to the local storage on the phone.
Now i would like store a .txt file as well in same directory.
I have tried several methods from stack overflow, the app doesn't complain but does not store the .txt as it should. I can't figure out why.
The methods of interest is: CreateTxt and generateNote. These are the ones that doesn't do what they are supposed to.
These methods are used within the startR.setOnClickListener method.
Can anybody see why? Thank you in advance.
package xxxx;
import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import static android.provider.AlarmClock.EXTRA_MESSAGE;
public class DataCollectionActivity extends AppCompatActivity {
private MediaPlayer mediaPLayer;
private MediaRecorder recorder;
private String OUTPUT_FILE;
public Button GoToUserAcc;
public Button GoToLogin;
public Button GoToTest;
// Permission Variables
private static final String LOG_TAG = "AudioRecordTest";
private static final int REQUEST_RECORD_AUDIO_PERMISSION = 200;
private static String mFileName = null;
private boolean permissionToRecordAccepted = false;
private String [] permissions =
{Manifest.permission.RECORD_AUDIO,
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.INTERNET};
private static final int
REQUEST_WRITE_EXTERNAL_STORAGE_PERMISSION = 200;
private boolean permissionToWriteExternalStoragedAccepted =
false;
private static final int REQUEST_INTERNET_PERMISSION = 200;
private boolean permissionToUseInternetAccepted = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_data_collec);
//Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
//setSupportActionBar(toolbar);
Button startR = (Button) findViewById(R.id.Bstart);
Button stopR = (Button) findViewById(R.id.Bstop);
Button playRecording = (Button) findViewById(R.id.playBtn);
Button stopPlaying = (Button) findViewById(R.id.stopBtn);
final TextView statusTV;
statusTV = (TextView) findViewById(R.id.tStatus);
OUTPUT_FILE= Environment.getExternalStorageDirectory().
getAbsolutePath()+"/audiorecorder.3gpp";
ActivityCompat.requestPermissions(this, permissions,
REQUEST_RECORD_AUDIO_PERMISSION);
/*------START recording BUTTON------*/
startR.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
final TextView stv=statusTV;
try {
beginRecording();
stv.setText("Recording");
//CreateTxt();
generateNote("MLdata", "sBody");
stv.setText("Created txt");
} catch (Exception e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
String exceptionAsString = sw.toString();
stv.setText("Error");
}
}
});
/*------STOP BUTTON------*/
stopR.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
final TextView stv=statusTV;
try {
stopRecording();
stv.setText("Stopped");
} catch (Exception e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
String exceptionAsString = sw.toString();
statusTV.setText("Error");
Log.d("here","dd",e);
}
}
});
}
private void stopPlayback() throws Exception{
if(mediaPLayer != null)
mediaPLayer.stop();
}
private void playRecording() throws IOException {
ditchMediaPLayer();
mediaPLayer = new MediaPlayer();
mediaPLayer.setDataSource(OUTPUT_FILE);
mediaPLayer.prepare();
mediaPLayer.start();
}
private void ditchMediaPLayer() {
if (mediaPLayer != null) {
try{
mediaPLayer.release();
} catch(Exception e) {
e.printStackTrace();
}
}
}
private void stopRecording() {
if(recorder != null)
recorder.stop();
}
private void beginRecording() throws Exception{
ditchMediaRecorder();
File outFile = new File(OUTPUT_FILE);
//DataCollectionActivity dca = new DataCollectionActivity();
//dca.CreateTxt();
if (outFile.exists()) {
outFile.delete();
}
recorder = new MediaRecorder();
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setOutputFormat(MediaRecorder.
OutputFormat.THREE_GPP);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
recorder.setOutputFile(OUTPUT_FILE);
/*API constraints
Container WAV
Encoding PCM
Rate 16K
Sample Format 16 bit OK
Channels Mono OK
*/
recorder.setAudioSamplingRate(16);
//channel 1 equals mono, 2 eqals stereo
recorder.setAudioChannels(1);
recorder.prepare();
recorder.start();
}
private void ditchMediaRecorder() {
if(recorder != null)
recorder.release();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
if (item.getItemId() == R.id.action_setting){
Toast.makeText(DataCollectionActivity.this, "You have
clicked on setting action menu", Toast.LENGTH_SHORT).show();
}
if (item.getItemId() == R.id.action_about_us){
Toast.makeText(DataCollectionActivity.this, "You have
clicked on about us action menu", Toast.LENGTH_SHORT).show();
goToUserAccount();
}
return super.onOptionsItemSelected(item);
}
// Requesting permission to RECORD_AUDIO
//fra android.com
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull
String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions,
grantResults);
switch (requestCode){
case REQUEST_RECORD_AUDIO_PERMISSION:
permissionToRecordAccepted = grantResults[0] ==
PackageManager.PERMISSION_GRANTED;
break;
}
if (!permissionToRecordAccepted ) finish();
//---ny permission ---
super.onRequestPermissionsResult(requestCode, permissions,
grantResults);
switch (requestCode){
case REQUEST_WRITE_EXTERNAL_STORAGE_PERMISSION:
permissionToWriteExternalStoragedAccepted =
grantResults[0] == PackageManager.PERMISSION_GRANTED;
break;
}
if (!permissionToRecordAccepted ) finish();
//---ny permission ---
super.onRequestPermissionsResult(requestCode, permissions,
grantResults);
switch (requestCode){
case REQUEST_INTERNET_PERMISSION:
permissionToUseInternetAccepted = grantResults[0] ==
PackageManager.PERMISSION_GRANTED;
break;
}
if (!permissionToRecordAccepted ) finish();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater mMenuInflater = getMenuInflater();
mMenuInflater.inflate(R.menu.menu_main, menu);
return true;
}
/** Opens up new activity */
//Vedrører tollbaren som ligenu ikke bliver brugt /virker ikke.
public void goToUserAccount() {
Intent intent = new Intent(this, UserAccountActivity.class);
EditText editText = (EditText)
findViewById(R.id.action_about_us);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
//Metode som laver en writer.
public void CreateTxt() throws IOException {
//concerning txt file
int id = 0;
String typeId = "S";
EditText db = (EditText) findViewById(R.id.dbNoiseText);
String dbString = db.getText().toString();
EditText numPar = (EditText)
findViewById(R.id.participatorsText);
String npar = numPar.getText().toString();
EditText conversationBool = (EditText)
findViewById(R.id.CoverationText);
String cBool = conversationBool.getText().toString();
File f = new File(Environment.getExternalStorageDirectory().
getAbsolutePath()+"dataForML.txt");
try {
System.out.print("enters try in createtxt");
PrintWriter writer = new PrintWriter(f, "UTF-8");
writer.println(dbString + ", ");
writer.println(npar + ", ");
writer.println(cBool + ", ");
writer.println(typeId + id + ", ");
writer.println(Environment.getExternalStorageDirectory().
getAbsolutePath()+"/dataForML.txt");
//Her skal den skrive binary. Metoden ligger i asrRequest
writer.println("Path to Acceleroeter CSV file ");
writer.println("\n");
writer.println();
writer.close();
id++;
} catch (IOException e) {
e.printStackTrace();
}
}
//OUTPUT_FILE= Environment.getExternalStorageDirectory().
getAbsolutePath()+"/audiorecorder.3gpp";
//generateNoteOnSD("MLdata", "sBody");
public void generateNote(String sFileName, String sBody) {
try {
File root = new
File(Environment.getExternalStorageDirectory().
getAbsolutePath(), "NotesML");
if (!root.exists()) {
root.mkdirs();
}
File gpxfile = new File(root, sFileName);
FileWriter writer = new FileWriter(gpxfile);
writer.append(sBody);
writer.flush();
writer.close();
//Toast.makeText(context, "Saved",
Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
}
public void thirdTry(){
String FILENAME = "hello_file";
String string = "hello world!";
try{
FileOutputStream fos = openFileOutput(FILENAME,
Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();
} catch (IOException e){
e.printStackTrace();
}
}
}
layout xml comes here
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="10dp"
android:layout_marginBottom="10dp"
android:layout_marginEnd="10dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginStart="10dp"
android:layout_marginTop="10dp"
android:orientation="vertical"
android:weightSum="1">
<EditText
android:id="#+id/dbNoiseText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="db noise"
android:inputType="textPersonName"
android:textAlignment="center"
android:textSize="24sp" />
<EditText
android:id="#+id/participatorsText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="# participators"
android:inputType="textPersonName"
android:textAlignment="center"
android:textSize="24sp" />
<EditText
android:id="#+id/CoverationText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Conversation? Y/N"
android:inputType="textPersonName"
android:textAlignment="center" />
<Button
android:id="#+id/Bstart"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:layout_marginBottom="10dp"
android:layout_marginEnd="10dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginStart="10dp"
android:layout_marginTop="10dp"
android:text="Start Recording" />
<Button
android:id="#+id/Bstop"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:layout_marginBottom="10dp"
android:layout_marginEnd="10dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginStart="10dp"
android:layout_marginTop="10dp"
android:text="Stop recording" />
<TextView
android:id="#+id/tStatus"
android:layout_width="354dp"
android:layout_height="42dp"
android:text="status"
android:textAlignment="center"
android:textSize="24sp" />
</LinearLayout>
Manifest comes here
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="dk.itu.percomp17.jumanji">
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<uses-permission android:name="android.permission.RECORD_AUDIO"
/>
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category
android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<activity android:name=".UserAccountActivity" />
<activity android:name=".RegisterActivity" />
<activity android:name=".LoginActivity"/>
<activity android:name=".DataCollectionActivity"/>
<activity android:name=".CallingjsActivity">
</activity>
</application>
</manifest>
I found out. Following method solved it.
// Once a file has been created, use this method to publicize
//the file as it can be seen !!
// But be sure to add "Context context;" outside of the method.
// Plus, remember to add "context = getApplicationContext ();" in the
//onCreate () method.
public void scanFile(String path) {
MediaScannerConnection.scanFile(context,
new String[] { path }, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Log.i("TAG", "Finished scanning " + path);
}
});
}
I have a Android App. I need to integrate admob. I have included the following code but banner ad is not displaying in main layout please help regarding this your answers will be appreciated and it would be a great help. thank you.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ads="http://schemas.android.com/apk/lib/com.google.ads"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/main_layout"
android:background="#drawable/hanumanji1"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".HanumanActivity" >
<Button
android:id="#+id/pause_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:background="#drawable/circle_shape_drawable"
android:text="#string/pau"
android:textColor="#ffff00" />
<Button
android:id="#+id/play_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:background="#drawable/circle_shape_drawable"
android:gravity="center"
android:text="#string/pl"
android:textColor="#ffff00" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:background="#drawable/circle_shape_drawable"
android:gravity="center"
android:text="#string/de"
android:textColor="#ffff00" />
<com.google.ads.AdView
android:id="#+id/adView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
ads:adSize="BANNER"
ads:adUnitId="xxxxxxxxxxxxxxxxxxxxxxxxxxxx"
ads:loadAdOnCreate="true"/>
</RelativeLayout>
MainActivity.java
package e.hanuman;
import e.hanuman.Constants;
import java.util.ArrayList;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
import com.google.ads.AdRequest;
import com.google.ads.AdSize;
import com.google.ads.AdView;
import e.hanuman.R;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.animation.ValueAnimator;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.AccelerateInterpolator;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
public class HanumanActivity extends Activity implements OnClickListener{
Button play_button, pause_button, button1 ;
private AdView adView;
MediaPlayer player;
private int[] LEAVES = {
R.drawable.leaf_green,
R.drawable.leaf_red,
R.drawable.leaf_yellow,
R.drawable.leaf_other,
};
private Rect mDisplaySize = new Rect();
private RelativeLayout mRootLayout;
private ArrayList<View> mAllImageViews = new ArrayList<View>();
private float mScale;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_hanuman);
// Create the adView
adView = new AdView(this, AdSize.BANNER, "xxxxxxxxxxxxxxxxxxxxxxxxxxxx");
// Lookup your LinearLayout assuming it's been given
// the attribute android:id="#+id/mainLayout"
RelativeLayout layout = (RelativeLayout)findViewById(R.id.main_layout);
// Add the adView to it
layout.addView(adView);
// Initiate a generic request to load it with an ad
adView.loadAd(new AdRequest());
AdView adView = (AdView)this.findViewById(R.id.adView);
AdRequest adRequest = new AdRequest();
//adRequest.setTesting(true);
button1=(Button)findViewById(R.id.button1);
button1.setOnClickListener(this);
TelephonyManager mgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
if(mgr != null) {
mgr.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
}
getInit();
Display display = getWindowManager().getDefaultDisplay();
display.getRectSize(mDisplaySize);
DisplayMetrics metrics = new DisplayMetrics();
display.getMetrics(metrics);
mScale = metrics.density;
mRootLayout = (RelativeLayout) findViewById(R.id.main_layout);
new Timer().schedule(new ExeTimerTask(), 0, 5000);
}
PhoneStateListener phoneStateListener = new PhoneStateListener() {
#Override
public void onCallStateChanged(int state, String incomingNumber) {
if (state == TelephonyManager.CALL_STATE_RINGING) {
player.pause();
} else if(state == TelephonyManager.CALL_STATE_IDLE) {
//Not in call: Play music
player.start();
} else if(state == TelephonyManager.CALL_STATE_OFFHOOK) {
//A call is dialing, active or on hold
player.pause();
}
super.onCallStateChanged(state, incomingNumber);
}
};
public void startAnimation(final ImageView aniView) {
aniView.setPivotX(aniView.getWidth()/2);
aniView.setPivotY(aniView.getHeight()/2);
long delay = new Random().nextInt(Constants.MAX_DELAY);
final ValueAnimator animator = ValueAnimator.ofFloat(0, 1);
animator.setDuration(Constants.ANIM_DURATION);
animator.setInterpolator(new AccelerateInterpolator());
animator.setStartDelay(delay);
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
int angle = 50 + (int)(Math.random() * 101);
int movex = new Random().nextInt(mDisplaySize.right);
#Override
public void onAnimationUpdate(ValueAnimator animation) {
float value = ((Float) (animation.getAnimatedValue())).floatValue();
aniView.setRotation(angle*value);
aniView.setTranslationX((movex-40)*value);
aniView.setTranslationY((mDisplaySize.bottom + (150*mScale))*value);
}
});
animator.start();
}
private Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
int viewId = new Random().nextInt(LEAVES.length);
Drawable d = getResources().getDrawable(LEAVES[viewId]);
LayoutInflater inflate = LayoutInflater.from(HanumanActivity.this);
ImageView imageView = (ImageView) inflate.inflate(R.layout.ani_image_view, null);
imageView.setImageDrawable(d);
mRootLayout.addView(imageView);
mAllImageViews.add(imageView);
LayoutParams animationLayout = (LayoutParams) imageView.getLayoutParams();
animationLayout.setMargins(0, (int)(-150*mScale), 0, 0);
animationLayout.width = (int) (60*mScale);
animationLayout.height = (int) (60*mScale);
startAnimation(imageView);
}
};
private class ExeTimerTask extends TimerTask {
#Override
public void run() {
// we don't really use the message 'what' but we have to specify something.
mHandler.sendEmptyMessage(Constants.EMPTY_MESSAGE_WHAT);
}
}
public void getInit() {
play_button = (Button) findViewById(R.id.play_button);
pause_button = (Button) findViewById(R.id.pause_button);
play_button.setOnClickListener(this);
pause_button.setOnClickListener(this);
player = MediaPlayer.create(this, R.raw.hanu);
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.play_button:
player.start();
break;
case R.id.pause_button:
player.pause();
break;
case R.id.button1:
button1Click();
break;
}}
private void button1Click() {
// TODO Auto-generated method stub
startActivity(new Intent("e.hanuman.details"));
}
#Override
public void onBackPressed(){
if(player != null && player.isPlaying())
player.stop();
finish();
}
#Override
public void onDestroy() {
if (adView != null) {
adView.destroy();
}
super.onDestroy();
}
}
MANIFEST XML
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="e.hanuman"
android:versionCode="4"
android:versionName="4.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<application
android:allowBackup="true"
android:icon="#drawable/hanuman"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity android:theme="#android:style/Theme.NoTitleBar.Fullscreen"
android:name="e.hanuman.Splash" android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="e.hanuman.HanumanActivity"
android:label="#string/app_name"
android:theme="#android:style/Theme.NoTitleBar.Fullscreen"
android:screenOrientation="portrait" >
</activity>
<activity
android:name="details"
android:theme="#android:style/Theme.NoTitleBar.Fullscreen"
android:label="#string/app_name"
android:screenOrientation="portrait" >
<intent-filter>
<action android:name="e.hanuman.details" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity android:name="com.google.ads.AdActivity"
android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"/>
</application>
</manifest>
Change com.google.android.ads to com.google.android.gms.ads In your main activity and your manifest because you're using the old ads, use the .gms change your xml too, to the .gms adview.