How can I check if a telephone number exist programmatically? - java

I want to do an Android App that check if a number exist or not. In particular I was thinking of calling the number to check and if it ring it means that exist, otherwise it does not.
At the moment I can read the state "IDLE" and "OFFHOOK" but not the state "CALL_STATE_RINGING" that as far as I understood trigger only for received call.
How can I understand when it is ringing and when the number is not valid?
Note: The calling approach is just an idea but I could accept others solutions if they are effective.
My code at the moment:
Listener:
public class EndCallListener extends PhoneStateListener {
private String TAG = "CALL_AUTOMATICALLY_LISTENER";
#Override
public void onCallStateChanged(int state, String incomingNumber) {
if(TelephonyManager.CALL_STATE_RINGING == state) {
// TODO
Log.i(TAG, "RINGING, number: " + incomingNumber);
}
if(TelephonyManager.CALL_STATE_OFFHOOK == state) {
Log.i(TAG, "OFFHOOK");
}
if(TelephonyManager.CALL_STATE_IDLE == state) {
Log.i(TAG, "IDLE");
}
}
}
public class MainActivity extends AppCompatActivity {
private String TAG = "CALL_AUTOMATICALLY";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
askPermission();
}
private void askPermission() {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CALL_PHONE},0);
}
public void startCall(View view) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(Manifest.permission.CALL_PHONE) == PackageManager.PERMISSION_GRANTED) {
String number = "+39555555555"; // fake number
Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse("tel:" + number));
// Activate listener
EndCallListener callListener = new EndCallListener();
TelephonyManager mTM = (TelephonyManager)this.getSystemService(Context.TELEPHONY_SERVICE);
if (mTM != null) mTM.listen(callListener, PhoneStateListener.LISTEN_CALL_STATE);
else Log.d(TAG, "TelephonyManager null");
// start call
startActivity(intent);
} else {
askPermission();
}
}
}
public void startCallNotExisting(View view) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(Manifest.permission.CALL_PHONE) == PackageManager.PERMISSION_GRANTED) {
String number = "+39456464564545555565656565";
Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse("tel:" + number));
// Activate listener
EndCallListener callListener = new EndCallListener();
TelephonyManager mTM = (TelephonyManager)this.getSystemService(Context.TELEPHONY_SERVICE);
if (mTM != null) mTM.listen(callListener, PhoneStateListener.LISTEN_CALL_STATE);
else Log.d(TAG, "TelephonyManager null");
// start call
startActivity(intent);
} else {
askPermission();
}
}
}
}

I suggest you check phone number regex instead of calling them.place this method in your helper or activity or fragment class
public static boolean validateMobile(String mobile) {
if (mobile.matches("^[+]?[0-9]{10,13}$")) {
return true;
} else {
return false;
}
}
And use it like
if(Helper.validateMobile(mobile){
//mobile is valid
}else{
//mobile is not valid}
also this regex can be different if you target one specific country.for example i use below regex for iran phone numbers
(\\+98|0)?9\\d{9}

Related

How to access location in background Android 12?

I am making an application that fetch last known location when user clicked power key two times. I am using foreground service to register the broadcast receiver and for location I am using fusedlocationproviderclient. The user can fetch the location while app is in background. My problem is I am only able to fetch location for one time only. Second time location is null. How can I solve it?
Note:
It is working fine in android 7 version.
Service:
public class ScreenOnOffBackgroundService extends Service {
private ScreenOnOffReceiver screenOnOffReceiver = null;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
createNotificationChannel();
Intent mainIntent = new Intent(this, DashboardActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this,0,mainIntent, 0);
Notification notification = new NotificationCompat.Builder(this,"safetyId")
.setContentTitle("Safety Service")
.setContentText("Press power key to send alert")
.setSmallIcon(R.drawable.android)
.setContentIntent(pendingIntent)
.build();
startForeground(1,notification);
return START_STICKY;
}
#Override
public void onCreate() {
super.onCreate();
// Create an IntentFilter instance.
IntentFilter intentFilter = new IntentFilter();
// Add network connectivity change action.
intentFilter.addAction("android.intent.action.SCREEN_ON");
// Set broadcast receiver priority.
intentFilter.setPriority(100);
screenOnOffReceiver = new ScreenOnOffReceiver();
HandlerThread broadcastHandlerThread = new HandlerThread("SafetyThread");
broadcastHandlerThread.start();
Looper looper = broadcastHandlerThread.getLooper();
Handler broadcastHandler = new Handler(looper);
registerReceiver(screenOnOffReceiver,intentFilter,null,broadcastHandler);
}
private void createNotificationChannel() {
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O ){
NotificationChannel channel = new NotificationChannel(
"safetyId",
"Safety Service",
NotificationManager.IMPORTANCE_DEFAULT
);
NotificationManager manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(channel);
}
}
#Override
public void onDestroy() {
stopForeground(true);
stopSelf();
// Unregister screenOnOffReceiver when destroy.
if(screenOnOffReceiver!=null)
{
unregisterReceiver(screenOnOffReceiver);
}
}
}
Broadcast Receiver:
public class ScreenOnOffReceiver extends BroadcastReceiver {
private int count = 0;
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (Intent.ACTION_SCREEN_ON.equals(action) || Intent.ACTION_SCREEN_OFF.equals(action)) {
count++;
if (count == 2) {
count = 0;
DashboardActivity.getInstance().getLastLocation();
}
}
}
}
Dashboard Activity:
public class DashboardActivity extends AppCompatActivity {
public Button btnAlert;
private static DashboardActivity instance;
private final static int REQUEST_CODE = 123;
private FusedLocationProviderClient locationProviderClient;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dashboard);
instance = this;
registerService();
btnAlert = findViewById(R.id.btnAlert);
locationProviderClient = LocationServices.getFusedLocationProviderClient(this);
btnAlert.setOnClickListener(view -> getLastLocation());
}
public static DashboardActivity getInstance(){
return instance;
}
public void registerService(){
if(!foregroundServiceRunning()){
Intent backgroundService = new Intent(this, ScreenOnOffBackgroundService.class);
ContextCompat.startForegroundService(this,backgroundService);
}
}
public boolean foregroundServiceRunning(){
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for(ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)){
if(ScreenOnOffBackgroundService.class.getName().equals(service.service.getClassName())){
return true;
}
}
return false;
}
#SuppressLint("MissingPermission")
public void getLastLocation() {
// check if permissions are given
if (checkPermissions()) {
// check if location is enabled
if (isLocationEnabled()) {
locationProviderClient.getLastLocation().addOnCompleteListener(task -> {
Location location = task.getResult();
if (location == null) {
requestNewLocationData();
} else {
Toast.makeText(this, "Latitude: "+location.getLatitude(), Toast.LENGTH_LONG).show();
}
});
} else {
Toast.makeText(this, "Please turn on your location", Toast.LENGTH_LONG).show();
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
} else {
requestPermissions();
}
}
private boolean checkPermissions() {
return ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED;
}
private void requestPermissions() {
String[] permissionArray = new String[]{
android.Manifest.permission.ACCESS_COARSE_LOCATION,
android.Manifest.permission.ACCESS_FINE_LOCATION,};
ActivityCompat.requestPermissions(this, permissionArray, REQUEST_CODE);
}
#SuppressLint("MissingPermission")
private void requestNewLocationData() {
LocationRequest mLocationRequest = LocationRequest.create()
.setInterval(100)
.setFastestInterval(3000)
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setMaxWaitTime(100).setNumUpdates(1);
locationProviderClient = LocationServices.getFusedLocationProviderClient(this);
locationProviderClient.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper());
}
private final LocationCallback mLocationCallback = new LocationCallback() {
#Override
public void onLocationResult(LocationResult locationResult) {
Location mLastLocation = locationResult.getLastLocation();
}
};
private boolean isLocationEnabled() {
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) || locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}
#Override
public void
onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQUEST_CODE) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
getLastLocation();
}
}
if (requestCode == 0) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
notifyPolice();
}
}
}
}
First off- DashboardActivity.getInstance()- NEVER DO THIS. You're assuming there's exactly 1 instance of an activity at all times. That's wrong. There can be 0. There can be 2. You can't make an activity a singleton. In addition, this always creates a memory leak. NEVER store an Activity in a static variable, this is always a memory leak. It's also (due to the first fact) wrong because it can point to the wrong instance of an Activity.
Secondly- you're using getLastLocation. Don't do that. That function is meant for optimization and will usually return null (I know the docs say the opposite. The docs there have always been wrong.) If you need the location, request it instead. getLastLocation should only be used to get a quick result optimisticly before requesting location updates.
Thirdly- your call to requestNewLocation is passing in a location handler that does nothing. It isn't even updating mLastLocation because that's a method level variable and not a class one.
Fourthly- did you read the new rules for background location processing in ANdroid 12? https://proandroiddev.com/android-12-privacy-changes-for-location-55ffd8c016fd
Those are just the major mistakes, not smaller things that make me go "huh?". With the best of intentions here- this code needs major refactoring. It feels like someone who didn't really understand Android cobbled it together from a dozen examples he didn't understand. If I were you I'd start by simplifying the concept- do one thing, understand it, and then do another. You're overreaching your abilities at the moment doing this all at once, and you'll be better off learning one thing at a time.

Where exactly to insert onPause() in Android?

Sorry for this question, I'm a beginner.
My first app has been rejected due to violating the Device and Network Abuse policy.
Edit: Main reason is that Youtube video doesn't stop playing when the display is turned off...
some info here:
Volating the Device and Network Abuse policy
I should add
#Override
public void onPause(){
super.onPause();
mWebView.onPause();
}
But where exactly I should insert this code?
Please help.
My Java code is here:
WebView asw_view;
ProgressBar asw_progress;
TextView asw_loading_text;
NotificationManager asw_notification;
Notification asw_notification_new;
private String asw_cam_message;
private ValueCallback<Uri> asw_file_message;
private ValueCallback<Uri[]> asw_file_path;
private final static int asw_file_req = 1;
private final static int loc_perm = 1;
private final static int file_perm = 2;
private SecureRandom random = new SecureRandom();
private static final String TAG = MainActivity.class.getSimpleName();
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
if (Build.VERSION.SDK_INT >= 21) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
getWindow().setStatusBarColor(getResources().getColor(R.color.colorPrimary));
Uri[] results = null;
if (resultCode == Activity.RESULT_OK) {
if (requestCode == asw_file_req) {
if (null == asw_file_path) {
return;
}
if (intent == null || intent.getData() == null) {
if (asw_cam_message != null) {
results = new Uri[]{Uri.parse(asw_cam_message)};
}
} else {
String dataString = intent.getDataString();
if (dataString != null) {
results = new Uri[]{ Uri.parse(dataString) };
} else {
if(ASWP_MULFILE) {
if (intent.getClipData() != null) {
final int numSelectedFiles = intent.getClipData().getItemCount();
results = new Uri[numSelectedFiles];
for (int i = 0; i < numSelectedFiles; i++) {
results[i] = intent.getClipData().getItemAt(i).getUri();
}
}
}
}
}
}
}
asw_file_path.onReceiveValue(results);
asw_file_path = null;
} else {
if (requestCode == asw_file_req) {
if (null == asw_file_message) return;
Uri result = intent == null || resultCode != RESULT_OK ? null : intent.getData();
asw_file_message.onReceiveValue(result);
asw_file_message = null;
}
}
}
#SuppressLint({"SetJavaScriptEnabled", "WrongViewCast"})
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.w("READ_PERM = ",Manifest.permission.READ_EXTERNAL_STORAGE);
Log.w("WRITE_PERM = ",Manifest.permission.WRITE_EXTERNAL_STORAGE);
//Prevent the app from being started again when it is still alive in the background
if (!isTaskRoot()) {
finish();
return;
}
setContentView(R.layout.activity_main);
if (ASWP_PBAR) {
asw_progress = findViewById(R.id.msw_progress);
} else {
findViewById(R.id.msw_progress).setVisibility(View.GONE);
}
asw_loading_text = findViewById(R.id.msw_loading_text);
Handler handler = new Handler();
//Launching app rating request
if (ASWP_RATINGS) {
handler.postDelayed(new Runnable() { public void run() { get_rating(); }}, 1000 * 60); //running request after few moments
}
//Getting basic device information
get_info();
//Getting GPS location of device if given permission
if(!check_permission(1)){
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, loc_perm);
}
get_location();
asw_view = findViewById(R.id.msw_view);
//Webview settings; defaults are customized for best performance
WebSettings webSettings = asw_view.getSettings();
if(!ASWP_OFFLINE){
webSettings.setJavaScriptEnabled(ASWP_JSCRIPT);
}
webSettings.setSaveFormData(ASWP_SFORM);
webSettings.setSupportZoom(ASWP_ZOOM);
webSettings.setGeolocationEnabled(ASWP_LOCATION);
webSettings.setAllowFileAccess(true);
webSettings.setAllowFileAccessFromFileURLs(true);
webSettings.setAllowUniversalAccessFromFileURLs(true);
webSettings.setUseWideViewPort(true);
webSettings.setDomStorageEnabled(true);
asw_view.setDownloadListener(new DownloadListener() {
#Override
public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimeType, long contentLength) {
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.setMimeType(mimeType);
String cookies = CookieManager.getInstance().getCookie(url);
request.addRequestHeader("cookie", cookies);
request.addRequestHeader("User-Agent", userAgent);
request.setDescription(getString(R.string.dl_downloading));
request.setTitle(URLUtil.guessFileName(url, contentDisposition, mimeType));
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, URLUtil.guessFileName(url, contentDisposition, mimeType));
DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
assert dm != null;
dm.enqueue(request);
Toast.makeText(getApplicationContext(), getString(R.string.dl_downloading2), Toast.LENGTH_LONG).show();
}
});
if (Build.VERSION.SDK_INT >= 21) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
getWindow().setStatusBarColor(getResources().getColor(R.color.colorPrimaryDark));
asw_view.setLayerType(View.LAYER_TYPE_HARDWARE, null);
webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
} else if (Build.VERSION.SDK_INT >= 19) {
asw_view.setLayerType(View.LAYER_TYPE_HARDWARE, null);
}
asw_view.setVerticalScrollBarEnabled(false);
asw_view.setWebViewClient(new Callback());
asw_view.getSettings().setLoadWithOverviewMode(true);
asw_view.getSettings().setUseWideViewPort(true);
asw_view.setInitialScale(1);
asw_view.getSettings().setJavaScriptEnabled(true);
//Rendering the default URL
aswm_view(ASWV_URL, false);
asw_view.setWebChromeClient(new WebChromeClient() {
//Handling input[type="file"] requests for android API 16+
public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture){
if(ASWP_FUPLOAD) {
asw_file_message = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType(ASWV_F_TYPE);
if(ASWP_MULFILE) {
i.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
}
startActivityForResult(Intent.createChooser(i, getString(R.string.fl_chooser)), asw_file_req);
}
}
//Handling input[type="file"] requests for android API 21+
public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams){
get_file();
if(ASWP_FUPLOAD) {
if (asw_file_path != null) {
asw_file_path.onReceiveValue(null);
}
asw_file_path = filePathCallback;
Intent takePictureIntent = null;
if (ASWP_CAMUPLOAD) {
takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(MainActivity.this.getPackageManager()) != null) {
File photoFile = null;
try {
photoFile = create_image();
takePictureIntent.putExtra("PhotoPath", asw_cam_message);
} catch (IOException ex) {
Log.e(TAG, "Image file creation failed", ex);
}
if (photoFile != null) {
asw_cam_message = "file:" + photoFile.getAbsolutePath();
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
} else {
takePictureIntent = null;
}
}
}
Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
if(!ASWP_ONLYCAM) {
contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
contentSelectionIntent.setType(ASWV_F_TYPE);
if (ASWP_MULFILE) {
contentSelectionIntent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
}
}
Intent[] intentArray;
if (takePictureIntent != null) {
intentArray = new Intent[]{takePictureIntent};
} else {
intentArray = new Intent[0];
}
Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
chooserIntent.putExtra(Intent.EXTRA_TITLE, getString(R.string.fl_chooser));
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);
startActivityForResult(chooserIntent, asw_file_req);
}
return true;
}
//Getting webview rendering progress
#Override
public void onProgressChanged(WebView view, int p) {
if (ASWP_PBAR) {
asw_progress.setProgress(p);
if (p == 100) {
asw_progress.setProgress(0);
}
}
}
// overload the geoLocations permissions prompt to always allow instantly as app permission was granted previously
public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) {
if(Build.VERSION.SDK_INT < 23 || (Build.VERSION.SDK_INT >= 23 && check_permission(1))){
// location permissions were granted previously so auto-approve
callback.invoke(origin, true, false);
} else {
// location permissions not granted so request them
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, loc_perm);
}
}
});
if (getIntent().getData() != null) {
String path = getIntent().getDataString();
/*
If you want to check or use specific directories or schemes or hosts
Uri data = getIntent().getData();
String scheme = data.getScheme();
String host = data.getHost();
List<String> pr = data.getPathSegments();
String param1 = pr.get(0);
*/
aswm_view(path, false);
}
}
#Override
public void onResume() {
super.onResume();
//Coloring the "recent apps" tab header; doing it onResume, as an insurance
if (Build.VERSION.SDK_INT >= 23) {
Bitmap bm = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
ActivityManager.TaskDescription taskDesc;
taskDesc = new ActivityManager.TaskDescription(getString(R.string.app_name), bm, getColor(R.color.colorPrimary));
MainActivity.this.setTaskDescription(taskDesc);
}
get_location();
}
//Setting activity layout visibility
private class Callback extends WebViewClient {
public void onPageStarted(WebView view, String url, Bitmap favicon) {
get_location();
}
public void onPageFinished(WebView view, String url) {
findViewById(R.id.msw_welcome).setVisibility(View.GONE);
findViewById(R.id.msw_view).setVisibility(View.VISIBLE);
}
//For android below API 23
#SuppressWarnings("deprecation")
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Toast.makeText(getApplicationContext(), getString(R.string.went_wrong), Toast.LENGTH_SHORT).show();
aswm_view("file:///android_res/raw/error.html", false);
}
//Overriding webview URLs
#SuppressWarnings("deprecation")
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return url_actions(view, url);
}
//Overriding webview URLs for API 23+ [suggested by github.com/JakePou]
#TargetApi(Build.VERSION_CODES.N)
#Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
return url_actions(view, request.getUrl().toString());
}
}
//Random ID creation function to help get fresh cache every-time webview reloaded
public String random_id() {
return new BigInteger(130, random).toString(32);
}
//Opening URLs inside webview with request
void aswm_view(String url, Boolean tab) {
if (tab) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
startActivity(intent);
} else {
if(url.contains("?")){ // check to see whether the url already has query parameters and handle appropriately.
url += "&";
} else {
url += "?";
}
url += "rid="+random_id();
asw_view.loadUrl(url);
}
}
//Actions based on shouldOverrideUrlLoading
public boolean url_actions(WebView view, String url){
boolean a = true;
//Show toast error if not connected to the network
if (!ASWP_OFFLINE && !DetectConnection.isInternetAvailable(MainActivity.this)) {
Toast.makeText(getApplicationContext(), getString(R.string.check_connection), Toast.LENGTH_SHORT).show();
//Use this in a hyperlink to redirect back to default URL :: href="refresh:android"
} else if (url.startsWith("refresh:")) {
aswm_view(ASWV_URL, false);
//Use this in a hyperlink to launch default phone dialer for specific number :: href="tel:+919876543210"
} else if (url.startsWith("tel:")) {
Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse(url));
startActivity(intent);
//Use this to open your apps page on google play store app :: href="rate:android"
} else if (url.startsWith("rate:")) {
final String app_package = getPackageName(); //requesting app package name from Context or Activity object
try {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + app_package)));
} catch (ActivityNotFoundException anfe) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + app_package)));
}
//Sharing content from your webview to external apps :: href="share:URL" and remember to place the URL you want to share after share:___
} else if (url.startsWith("share:")) {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_SUBJECT, view.getTitle());
intent.putExtra(Intent.EXTRA_TEXT, view.getTitle()+"\nVisit: "+(Uri.parse(url).toString()).replace("share:",""));
startActivity(Intent.createChooser(intent, getString(R.string.share_w_friends)));
//Use this in a hyperlink to exit your app :: href="exit:android"
} else if (url.startsWith("exit:")) {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
//Opening external URLs in android default web browser
} else if (ASWP_EXTURL && !aswm_host(url).equals(ASWV_HOST)) {
aswm_view(url,true);
} else {
a = false;
}
return a;
}
//Getting host name
public static String aswm_host(String url){
if (url == null || url.length() == 0) {
return "";
}
int dslash = url.indexOf("//");
if (dslash == -1) {
dslash = 0;
} else {
dslash += 2;
}
int end = url.indexOf('/', dslash);
end = end >= 0 ? end : url.length();
int port = url.indexOf(':', dslash);
end = (port > 0 && port < end) ? port : end;
Log.w("URL Host: ",url.substring(dslash, end));
return url.substring(dslash, end);
}
//Getting device basic information
public void get_info(){
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.setAcceptCookie(true);
cookieManager.setCookie(ASWV_URL, "DEVICE=android");
cookieManager.setCookie(ASWV_URL, "DEV_API=" + Build.VERSION.SDK_INT);
}
//Checking permission for storage and camera for writing and uploading images
public void get_file(){
String[] perms = {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA};
//Checking for storage permission to write images for upload
if (ASWP_FUPLOAD && ASWP_CAMUPLOAD && !check_permission(2) && !check_permission(3)) {
ActivityCompat.requestPermissions(MainActivity.this, perms, file_perm);
//Checking for WRITE_EXTERNAL_STORAGE permission
} else if (ASWP_FUPLOAD && !check_permission(2)) {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, file_perm);
//Checking for CAMERA permissions
} else if (ASWP_CAMUPLOAD && !check_permission(3)) {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.CAMERA}, file_perm);
}
}
//Using cookies to update user locations
public void get_location(){
//Checking for location permissions
if (ASWP_LOCATION && ((Build.VERSION.SDK_INT >= 23 && check_permission(1)) || Build.VERSION.SDK_INT < 23)) {
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.setAcceptCookie(true);
GPSTrack gps;
gps = new GPSTrack(MainActivity.this);
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
if (gps.canGetLocation()) {
if (latitude != 0 || longitude != 0) {
cookieManager.setCookie(ASWV_URL, "lat=" + latitude);
cookieManager.setCookie(ASWV_URL, "long=" + longitude);
//Log.w("New Updated Location:", latitude + "," + longitude); //enable to test dummy latitude and longitude
} else {
Log.w("New Updated Location:", "NULL");
}
} else {
show_notification(1, 1);
Log.w("New Updated Location:", "FAIL");
}
}
}
//Checking if particular permission is given or not
public boolean check_permission(int permission){
switch(permission){
case 1:
return ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED;
case 2:
return ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED;
case 3:
return ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED;
}
return false;
}
//Creating image file for upload
private File create_image() throws IOException {
#SuppressLint("SimpleDateFormat")
String file_name = new SimpleDateFormat("yyyy_mm_ss").format(new Date());
String new_name = "file_"+file_name+"_";
File sd_directory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
return File.createTempFile(new_name, ".jpg", sd_directory);
}
//Launching app rating dialoge [developed by github.com/hotchemi]
public void get_rating() {
if (DetectConnection.isInternetAvailable(MainActivity.this)) {
AppRate.with(this)
.setStoreType(StoreType.GOOGLEPLAY) //default is Google Play, other option is Amazon App Store
.setInstallDays(SmartWebView.ASWR_DAYS)
.setLaunchTimes(SmartWebView.ASWR_TIMES)
.setRemindInterval(SmartWebView.ASWR_INTERVAL)
.setTitle(R.string.rate_dialog_title)
.setMessage(R.string.rate_dialog_message)
.setTextLater(R.string.rate_dialog_cancel)
.setTextNever(R.string.rate_dialog_no)
.setTextRateNow(R.string.rate_dialog_ok)
.monitor();
AppRate.showRateDialogIfMeetsConditions(this);
}
//for more customizations, look for AppRate and DialogManager
}
//Creating custom notifications with IDs
public void show_notification(int type, int id) {
long when = System.currentTimeMillis();
asw_notification = (NotificationManager) MainActivity.this.getSystemService(Context.NOTIFICATION_SERVICE);
Intent i = new Intent();
if (type == 1) {
i.setClass(MainActivity.this, MainActivity.class);
} else if (type == 2) {
i.setAction(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
} else {
i.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
i.addCategory(Intent.CATEGORY_DEFAULT);
i.setData(Uri.parse("package:" + MainActivity.this.getPackageName()));
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
i.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
}
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(MainActivity.this, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);
Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder builder = new NotificationCompat.Builder(MainActivity.this, "");
switch(type){
case 1:
builder.setTicker(getString(R.string.app_name));
builder.setContentTitle(getString(R.string.loc_fail));
builder.setContentText(getString(R.string.loc_fail_text));
builder.setStyle(new NotificationCompat.BigTextStyle().bigText(getString(R.string.loc_fail_more)));
builder.setVibrate(new long[]{350,350,350,350,350});
builder.setSmallIcon(R.mipmap.ic_launcher);
break;
case 2:
builder.setTicker(getString(R.string.app_name));
builder.setContentTitle(getString(R.string.loc_perm));
builder.setContentText(getString(R.string.loc_perm_text));
builder.setStyle(new NotificationCompat.BigTextStyle().bigText(getString(R.string.loc_perm_more)));
builder.setVibrate(new long[]{350, 700, 350, 700, 350});
builder.setSound(alarmSound);
builder.setSmallIcon(R.mipmap.ic_launcher);
break;
}
builder.setOngoing(false);
builder.setAutoCancel(true);
builder.setContentIntent(pendingIntent);
builder.setWhen(when);
builder.setContentIntent(pendingIntent);
asw_notification_new = builder.build();
asw_notification.notify(id, asw_notification_new);
}
//Checking if users allowed the requested permissions or not
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String permissions[], #NonNull int[] grantResults){
switch (requestCode){
case 1: {
if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
get_location();
}
}
}
}
//Action on back key tap/click
#Override
public boolean onKeyDown(int keyCode, #NonNull KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
if (asw_view.canGoBack()) {
asw_view.goBack();
} else {
finish();
}
return true;
}
}
return super.onKeyDown(keyCode, event);
}
#Override
protected void onStart() {
super.onStart();
}
#Override
protected void onStop() {
super.onStop();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
#Override
protected void onSaveInstanceState(Bundle outState ){
super.onSaveInstanceState(outState);
asw_view.saveState(outState);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState){
super.onRestoreInstanceState(savedInstanceState);
asw_view.restoreState(savedInstanceState);
}
}
Anywhere you want inside your Activity class (the one you pasted in your question).
I usually try to order my lifecycle methods in the order Android executes them, so I'd put it after onResume()
#Override
public void onResume() {
super.onResume();
asm_view.onResume(); //remember to add this so your WebView can resume
//Coloring the "recent apps" tab header; doing it onResume, as an insurance
if (Build.VERSION.SDK_INT >= 23) {
Bitmap bm = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
ActivityManager.TaskDescription taskDesc;
taskDesc = new ActivityManager.TaskDescription(getString(R.string.app_name), bm, getColor(R.color.colorPrimary));
MainActivity.this.setTaskDescription(taskDesc);
}
get_location();
}
#Ovveride
public void onPause() {
super.onPause();
asw_view.onPause(); //your WebView variable is asm_view, not mWebView, which is just example code
}
onPause is a lifecycle method of Activity (and Fragments) and can be placed anywhere in the Activity class but putting your lifecycle methods in the order they are executed will help making your code more readable.

Check if there is network/aeroplane mode active?

I have an application which uses a Google PlacePicker and Google StreetView. I have to test the application with the device in aeroplane mode.
I want the application to check when it reaches this activity if aeroplane mode is active, if it is not active I would like a Toast displayed
Below is the code for an Activity an activity in which there are 2 buttons, one of the buttons loads the PlacePicker and the other loads another activity which contains the StreetView.
I have seen this How can one detect airplane mode on Android? answer and that is where I got the code I have attempted in my answer but it will not work
Can someone please tell me how to get this working
public class PlacePickerActivity extends AppCompatActivity {
int PLACE_PICKER_REQUEST = 1;
TextView tvPlace;
private Button buttonStepsActivity;
private Button buttonStreet;
private boolean isAirplaneModeOn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_place_picker);
tvPlace = (TextView)findViewById(R.id.tvPlace);
//StreetView
buttonStreet = (Button) findViewById(R.id.buttonStreet);
if(isAirplaneModeOn) {
Toast.makeText(this,"Aeroplane mode active",Toast.LENGTH_LONG).show();
}
}
private static boolean isAirplaneModeOn(Context context) {
return Settings.System.getInt(context.getContentResolver(),
Settings.System.AIRPLANE_MODE_ON, 0) != 0;
}
public void goPlacePicker(View v) {
// Construct an intent for the place picker
try {
PlacePicker.IntentBuilder intentBuilder =
new PlacePicker.IntentBuilder();
Intent intent = intentBuilder.build(this);
// Start the intent by requesting a result,
// identified by a request code.
startActivityForResult(intentBuilder.build(this), PLACE_PICKER_REQUEST);
} catch (GooglePlayServicesRepairableException e) {
e.printStackTrace();
} catch (GooglePlayServicesNotAvailableException e) {
e.printStackTrace();
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PLACE_PICKER_REQUEST) {
if (resultCode == RESULT_OK) {
Place place = PlacePicker.getPlace(data, this);
String toastMsg = String.format("You have chosen: %s", place.getName());
Toast.makeText(this, toastMsg, Toast.LENGTH_LONG).show();
}
}
}
Use this way
find network enable
public static boolean isNetworkAvailable(Context mContext) {
ConnectivityManager connectivity = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null) {
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null) {
for (int i = 0; i < info.length; i++) {
if (info[i].getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
}
}
return false;
}
find aeroplane mode enable
private static boolean isAirplaneModeOn(Context context) {
return Settings.System.getInt(context.getContentResolver(),
Settings.System.AIRPLANE_MODE_ON, 0) != 0;
}
add this permission
<uses-permission android:name="android.permission.WRITE_SETTINGS" />

Use session initiation protocol on Android as service

i'm trying to implement a SIP Client on Android application using native Session Initiation protocol.
Everything is woking fine if i create an Activity and put the following code :
public class WalkieTalkieActivity extends AppCompatActivity implements View.OnTouchListener {
public String sipAddress = null;
public SipManager manager = null;
public SipProfile me = null;
public SipAudioCall call = null;
public IncomingCallReceiver callReceiver;
private static final int CALL_ADDRESS = 1;
private static final int SET_AUTH_INFO = 2;
private static final int UPDATE_SETTINGS_DIALOG = 3;
private static final int HANG_UP = 4;
private final int PERMISSIONS_REQUEST_RECORD_AUDIO = 1;
private final int PERMISSIONS_REQUEST_USE_SIP = 2;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_walkietalkie);
//initRecorderParameters(new int[]{8000, 11025, 16000, 22050, 44100});
//Richiedo i vari permessi
if (!hasUseSipPermission()) { requestUseSipPermission(); }
//Rchiedo i vari permessi
if (!hasRecordAudioPermission()) { requestRecordAudioPermission(); }
if (!SipManager.isVoipSupported(this)) {
//Visualizzo il messaggio voip non supportato e torno alla dahboard
Toast.makeText(WalkieTalkieActivity.this, "Voip non supportato su questo telefono", Toast.LENGTH_LONG).show();
Intent dashboard = new Intent(WalkieTalkieActivity.this,MainActivity.class);
// passo all'attivazione dell'activity page1.java
startActivity(dashboard);
finish();
}
if (!SipManager.isApiSupported(this)) {
//Visualizzo il messaggio voip non supportato e torno alla dahboard
Toast.makeText(WalkieTalkieActivity.this, "API non supportate su questo telefono", Toast.LENGTH_LONG).show();
Intent dashboard = new Intent(WalkieTalkieActivity.this,MainActivity.class);
// passo all'attivazione dell'activity page1.java
startActivity(dashboard);
finish();
}
// "Push to talk" can be a serious pain when the screen keeps turning off.
// Let's prevent that.
//getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
// use this to start and trigger a service
Intent i = new Intent(this, SipEngine.class);
// potentially add data to the intent
i.putExtra("KEY1", "Value to be used by the service");
this.startService(i);
initializeManager();
}
#Override
public void onStart() {
super.onStart();
// When we get back from the preference setting Activity, assume
// settings have changed, and re-login with new auth info.
initializeManager();
}
#Override
public void onDestroy() {
super.onDestroy();
if (call != null) {
call.close();
}
closeLocalProfile();
if (callReceiver != null) {
this.unregisterReceiver(callReceiver);
}
}
public void initializeManager() {
if(manager == null) {
manager = SipManager.newInstance(this);
}
initializeLocalProfile();
}
/**
* Logs you into your SIP provider, registering this device as the location to
* send SIP calls to for your SIP address.
*/
public void initializeLocalProfile() {
if (manager == null) {
return;
}
if (me != null) {
closeLocalProfile();
}
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
//String username = prefs.getString("namePref", "");
//String domain = prefs.getString("domainPref", "");
//String password = prefs.getString("passPref", "");
String username = "username";
String domain = "domain";
String password = "password";
// Set up the intent filter. This will be used to fire an
// IncomingCallReceiver when someone calls the SIP address used by this
// application.
IntentFilter filter = new IntentFilter();
filter.addAction("android.vohippo.INCOMING_CALL");
callReceiver = new IncomingCallReceiver();
this.registerReceiver(callReceiver, filter);
try {
Log.d("VOHIPPOSERVICE", "PROVO A REGISTRARE");
SipProfile.Builder builder = new SipProfile.Builder(username, domain);
builder.setPassword(password);
//Costruisco il builder
me = builder.build();
//Intent
Intent i = new Intent();
i.setAction("android.vohippo.INCOMING_CALL");
PendingIntent pi = PendingIntent.getBroadcast(this, 0, i, Intent.FILL_IN_DATA);
manager.open(me, pi, null);
// This listener must be added AFTER manager.open is called,
// Otherwise the methods aren't guaranteed to fire.
manager.setRegistrationListener(me.getUriString(), new SipRegistrationListener() {
public void onRegistering(String localProfileUri) {
updateStatus("Registering with SIP Server...");
//updateNotification(ContextCompat.getColor(getBaseContext(), R.color.colorPrimary), "Attivazione in corso...");
}
public void onRegistrationDone(String localProfileUri, long expiryTime) {
updateStatus("Ready");
//updateNotification(ContextCompat.getColor(getBaseContext(), R.color.colorPrimary), "Servizio disponibile");
}
public void onRegistrationFailed(String localProfileUri, int errorCode,
String errorMessage) {
updateStatus("Registration failed. Please check settings.");
//updateNotification(ContextCompat.getColor(getBaseContext(), R.color.colorPrimary), "Servizio non disponibile");
}
});
} catch (ParseException pe) {
updateStatus("Connection Error.");
//updateNotification(ContextCompat.getColor(getBaseContext(), R.color.colorPrimary), "Errore di connessione");
} catch (SipException se) {
updateStatus("Connection error.");
//updateNotification(ContextCompat.getColor(getBaseContext(), R.color.colorPrimary), "Errore connessione");
}
}
/**
* Closes out your local profile, freeing associated objects into memory
* and unregistering your device from the server.
*/
public void closeLocalProfile() {
if (manager == null) {
return;
}
try {
if (me != null) {
manager.close(me.getUriString());
}
} catch (Exception ee) {
Log.d("WalkieTalkieActivity", "Failed to close local profile.", ee);
}
}
/**
* Make an outgoing call.
*/
public void initiateCall() {
Toast.makeText(WalkieTalkieActivity.this, "Chiamata lanciata", Toast.LENGTH_SHORT).show();
updateStatus(sipAddress);
try {
SipAudioCall.Listener listener = new SipAudioCall.Listener() {
// Much of the client's interaction with the SIP Stack will
// happen via listeners. Even making an outgoing call, don't
// forget to set up a listener to set things up once the call is established.
#Override
public void onCallEstablished(SipAudioCall call) {
call.startAudio();
call.setSpeakerMode(true);
if (call.isMuted()) {
call.toggleMute();
}
updateStatus(call);
Toast.makeText(WalkieTalkieActivity.this, "Chiamata stabilita", Toast.LENGTH_SHORT).show();
}
#Override
public void onCallEnded(SipAudioCall call) {
Toast.makeText(WalkieTalkieActivity.this, "Chiamata terminata", Toast.LENGTH_SHORT).show();
updateStatus("Ready.");
}
};
call = manager.makeAudioCall(me.getUriString(), sipAddress, listener, 30);
}
catch (Exception e) {
Log.i("WalkieTalkieActivity", "Error when trying to close manager.", e);
if (me != null) {
try {
manager.close(me.getUriString());
} catch (Exception ee) {
Log.i("WalkieTalkieActivity",
"Error when trying to close manager.", ee);
ee.printStackTrace();
}
}
if (call != null) {
call.close();
}
}
}
/**
* Updates the status box at the top of the UI with a messege of your choice.
* #param status The String to display in the status box.
*/
public void updateStatus(final String status) {
// Be a good citizen. Make sure UI changes fire on the UI thread.
this.runOnUiThread(new Runnable() {
public void run() {
TextView labelView = (TextView) findViewById(R.id.sipLabel);
labelView.setText(status);
}
});
}
/**
* Updates the status box with the SIP address of the current call.
* #param call The current, active call.
*/
public void updateStatus(SipAudioCall call) {
String useName = call.getPeerProfile().getDisplayName();
if(useName == null) {
useName = call.getPeerProfile().getUserName();
}
updateStatus(useName + "#" + call.getPeerProfile().getSipDomain());
}
/**
* Updates whether or not the user's voice is muted, depending on whether the button is pressed.
* #param v The View where the touch event is being fired.
* #param event The motion to act on.
* #return boolean Returns false to indicate that the parent view should handle the touch event
* as it normally would.
*/
public boolean onTouch(View v, MotionEvent event) {
if (call == null) {
return false;
} else if (event.getAction() == MotionEvent.ACTION_DOWN && call != null && call.isMuted()) {
call.toggleMute();
} else if (event.getAction() == MotionEvent.ACTION_UP && !call.isMuted()) {
call.toggleMute();
}
return false;
}
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(0, CALL_ADDRESS, 0, "Call someone");
menu.add(0, SET_AUTH_INFO, 0, "Edit your SIP Info.");
menu.add(0, HANG_UP, 0, "End Current Call.");
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case CALL_ADDRESS:
showDialog(CALL_ADDRESS);
break;
case SET_AUTH_INFO:
updatePreferences();
break;
case HANG_UP:
if(call != null) {
try {
call.endCall();
} catch (SipException se) {
Log.d("WalkieTalkieActivity",
"Error ending call.", se);
}
call.close();
}
break;
}
return true;
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case CALL_ADDRESS:
LayoutInflater factory = LayoutInflater.from(this);
final View textBoxView = factory.inflate(R.layout.call_address_dialog, null);
return new AlertDialog.Builder(this)
.setTitle("Call Someone.")
.setView(textBoxView)
.setPositiveButton(
android.R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
EditText textField = (EditText)
(textBoxView.findViewById(R.id.calladdress_edit));
sipAddress = textField.getText().toString();
initiateCall();
}
})
.setNegativeButton(
android.R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Noop.
}
})
.create();
case UPDATE_SETTINGS_DIALOG:
return new AlertDialog.Builder(this)
.setMessage("Please update your SIP Account Settings.")
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
updatePreferences();
}
})
.setNegativeButton(
android.R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Noop.
}
})
.create();
}
return null;
}
public void updatePreferences() {
//Intent settingsActivity = new Intent(getBaseContext(),
// SipSettings.class);
//startActivity(settingsActivity);
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case PERMISSIONS_REQUEST_USE_SIP:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(WalkieTalkieActivity.this, "Permission Granted!", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(WalkieTalkieActivity.this, "Permission Denied!", Toast.LENGTH_SHORT).show();
}
case PERMISSIONS_REQUEST_RECORD_AUDIO:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(WalkieTalkieActivity.this, "Permission Granted!", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(WalkieTalkieActivity.this, "Permission Denied!", Toast.LENGTH_SHORT).show();
}
}
}
//Controllo che il sistema abbia il permesso di registrare audio
private boolean hasRecordAudioPermission(){
boolean hasPermission = (ContextCompat.checkSelfPermission(this,
Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED);
Log.d("VOHIPPO", "Permesso di registrare audio? " + hasPermission);
return hasPermission;
}
private void requestRecordAudioPermission(){
String requiredPermission = Manifest.permission.RECORD_AUDIO;
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
requiredPermission)) {
Toast.makeText(WalkieTalkieActivity.this, "Quest applicazione richiede il permesso di registrare audio", Toast.LENGTH_SHORT).show();
}
// request the permission.
ActivityCompat.requestPermissions(this,
new String[]{requiredPermission},
PERMISSIONS_REQUEST_RECORD_AUDIO);
}
//Controllo che il sistema abbia il permesso di registrare audio
private boolean hasUseSipPermission(){
boolean hasPermission = (ContextCompat.checkSelfPermission(this,
Manifest.permission.USE_SIP) == PackageManager.PERMISSION_GRANTED);
Log.d("VOHIPPO", "Permesso di usare sip? " + hasPermission);
return hasPermission;
}
private void requestUseSipPermission(){
String requiredPermission = Manifest.permission.USE_SIP;
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
requiredPermission)) {
Toast.makeText(WalkieTalkieActivity.this, "Quest applicazione richiede il permesso di usare SIP", Toast.LENGTH_SHORT).show();
}
// request the permission.
ActivityCompat.requestPermissions(this,
new String[]{requiredPermission},
PERMISSIONS_REQUEST_USE_SIP);
}
but if i create a service and try to do the same into this service i have no errors, but my client doesn't register with the server.
This is the code i put into the service :
public class SipEngine extends IntentService {
public String sipAddress = null;
public SipManager manager = null;
public SipProfile me = null;
public SipAudioCall call = null;
public IncomingCallReceiver callReceiver;
private static final int CALL_ADDRESS = 1;
private static final int SET_AUTH_INFO = 2;
private static final int UPDATE_SETTINGS_DIALOG = 3;
private static final int HANG_UP = 4;
private int NOTIFICATION = 10002; //Any unique number for this notification
public SipEngine() {
super("SipEngine");
}
#Override
protected void onHandleIntent(Intent workIntent) {
// Gets data from the incoming Intent
String dataString = workIntent.getDataString();
initializeManager();
sendNotification();
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//#Override
//public void onStart() {
// super.onStart();
// When we get back from the preference setting Activity, assume
// settings have changed, and re-login with new auth info.
//initializeManager();
//}
#Override
public void onDestroy() {
super.onDestroy();
if (call != null) {
call.close();
}
closeLocalProfile();
if (callReceiver != null) {
this.unregisterReceiver(callReceiver);
}
}
public void initializeManager() {
if(manager == null) {
manager = SipManager.newInstance(this);
}
initializeLocalProfile();
}
/**
* Logs you into your SIP provider, registering this device as the location to
* send SIP calls to for your SIP address.
*/
public void initializeLocalProfile() {
if (manager == null) {
return;
}
if (me != null) {
closeLocalProfile();
}
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
//String username = prefs.getString("namePref", "");
//String domain = prefs.getString("domainPref", "");
//String password = prefs.getString("passPref", "");
String username = "username";
String domain = "server";
String password = "password";
// Set up the intent filter. This will be used to fire an
// IncomingCallReceiver when someone calls the SIP address used by this
// application.
IntentFilter filter = new IntentFilter();
filter.addAction("android.vohippo.INCOMING_CALL");
callReceiver = new IncomingCallReceiver();
this.registerReceiver(callReceiver, filter);
try {
Log.d("VOHIPPOSERVICE", "PROVO A REGISTRARE");
SipProfile.Builder builder = new SipProfile.Builder(username, domain);
builder.setPassword(password);
//Costruisco il builder
me = builder.build();
//Intent
Intent i = new Intent();
i.setAction("android.vohippo.INCOMING_CALL");
PendingIntent pi = PendingIntent.getBroadcast(this, 0, i, Intent.FILL_IN_DATA);
manager.open(me, pi, null);
// This listener must be added AFTER manager.open is called,
// Otherwise the methods aren't guaranteed to fire.
manager.setRegistrationListener(me.getUriString(), new SipRegistrationListener() {
public void onRegistering(String localProfileUri) {
//updateStatus("Registering with SIP Server...");
updateNotification(ContextCompat.getColor(getBaseContext(), R.color.colorPrimary), "Attivazione in corso...");
}
public void onRegistrationDone(String localProfileUri, long expiryTime) {
//updateStatus("Ready");
updateNotification(ContextCompat.getColor(getBaseContext(), R.color.colorPrimary), "Servizio disponibile");
}
public void onRegistrationFailed(String localProfileUri, int errorCode,
String errorMessage) {
//updateStatus("Registration failed. Please check settings.");
updateNotification(ContextCompat.getColor(getBaseContext(), R.color.colorPrimary), "Servizio non disponibile");
}
});
} catch (ParseException pe) {
//updateStatus("Connection Error.");
//updateNotification(ContextCompat.getColor(getBaseContext(), R.color.colorPrimary), "Errore di connessione");
} catch (SipException se) {
//updateStatus("Connection error.");
//updateNotification(ContextCompat.getColor(getBaseContext(), R.color.colorPrimary), "Errore connessione");
}
}
/**
* Closes out your local profile, freeing associated objects into memory
* and unregistering your device from the server.
*/
public void closeLocalProfile() {
if (manager == null) {
return;
}
try {
if (me != null) {
manager.close(me.getUriString());
}
} catch (Exception ee) {
Log.d("WalkieTalkieActivity", "Failed to close local profile.", ee);
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Send simple notification using the NotificationCompat API.
*/
public void sendNotification() {
// Use NotificationCompat.Builder to set up our notification.
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
//icon appears in device notification bar and right hand corner of notification
builder.setSmallIcon(R.drawable.ic_service_sip);
// This intent is fired when notification is clicked
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://stacktips.com/"));
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
// Set the intent that will fire when the user taps the notification.
builder.setContentIntent(pendingIntent);
// Large icon appears on the left of the notification
builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_service_sip));
// Content title, which appears in large type at the top of the notification
builder.setContentTitle("Vohippo");
int color = ContextCompat.getColor(this, R.color.colorPrimary);
builder.setColor(color);
// Content text, which appears in smaller text below the title
builder.setContentText("491023456");
// The subtext, whichppears under the text on newer devices.
// This will show-up in the devices with Android 4.2 and above only
builder.setSubText("Attendere...");
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
// Will display the notification in the notification bar
notificationManager.notify(NOTIFICATION, builder.build());
}
/**
* Send simple notification using the NotificationCompat API.
*/
public void updateNotification(int color, String status) {
// Use NotificationCompat.Builder to set up our notification.
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.setColor(color);
// The subtext, which appears under the text on newer devices.
// This will show-up in the devices with Android 4.2 and above only
builder.setSubText(status);
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
// Will display the notification in the notification bar
notificationManager.notify(NOTIFICATION, builder.build());
}
Should i do something different into a service instead of a normal Activity?
Than k you.

android wear message api start activity and methods

I have a problem with the android wear device I can turn on the camera with the message api by loading turnOn() onCreate on mobile device.
Problem One: I can't open an activity if the phone is locked.
Problem Two: I can start only one activity if the phone is unlocked but can't call methods of the phone. The only way I started the camera was starting the MainActivity on the Oncreate() method using the wearListener service.
I want something like this app: https://play.google.com/store/apps/details?id=com.jumpbyte.flashlight
Here is my code:
Oncreate method phone
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = getIntent() ;
int valor = intent.getIntExtra("parameter",0);
String value = "key" ;
if (valor == 0){
boolean isCameraFlash = getApplicationContext().getPackageManager()
.hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
if(!isCameraFlash) {
showCameraAlert();
} else {
camera = Camera.open();
params = camera.getParameters();
}
if(isFlashlightOn) {
setFlashlightOff();
} else {
setFlashlightOn();
}
}
else{
finish();
}
/* boolean isCameraFlash = getApplicationContext().getPackageManager()
.hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
if(!isCameraFlash) {
showCameraAlert();
} else {
camera = Camera.open();
params = camera.getParameters();
}
if(isFlashlightOn) {
setFlashlightOff();
} else {
setFlashlightOn();
}
*/
}
Listener phone:
private static final String HELLO_WORLD_WEAR_PATH = "/hello-world-wear" ;
public void onMessageReceived(MessageEvent messageEvent) {
if (messageEvent.getPath().equals(HELLO_WORLD_WEAR_PATH)) {
// AudioManager audiomanager ;
// audiomanager = (AudioManager)getSystemService(Context.AUDIO_SERVICE) ;
// audiomanager = (AudioManager)getSystemService(Context.AUDIO_SERVICE) ;
// audiomanager.adjustVolume(AudioManager.ADJUST_RAISE, AudioManager.FLAG_SHOW_UI) ;
// Toast.makeText(getApplicationContext(), "Volume Up | Vibration Time Increased", Toast.LENGTH_SHORT).show() ;
//light lightOne = new light();
// MainActivity one = new MainActivity() ;
// one.messageone();
// lightOne.on();
// Toast.makeText(getApplicationContext(),
// "Button is clicked", Toast.LENGTH_LONG).show() ;
Intent startIntent = new Intent(this, MainActivity.class) ;
startIntent.putExtra("parameter", 0); //Optional parameters
startIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) ;
startActivity(startIntent) ;
/* if(isFlashlightOn) {
setFlashlightOff();
} else {
setFlashlightOn();
}
*/
} else {
} } }
Wear main class:
private void sendMessage() {
if (mNode != null && mGoogleApiClient!=null && mGoogleApiClient.isConnected()) {
Wearable.MessageApi.sendMessage(
mGoogleApiClient, mNode.getId(), HELLO_WORLD_WEAR_PATH, null).setResultCallback(
new ResultCallback<MessageApi.SendMessageResult>() {
#Override
public void onResult(MessageApi.SendMessageResult sendMessageResult) {
if (!sendMessageResult.getStatus().isSuccess()) {
Log.e("TAG", "Failed to send message with status code: "
+ sendMessageResult.getStatus().getStatusCode());
}
}
}
);
}else{ } }
protected void onStart() {
super.onStart() ;
if (!mResolvingError) {
mGoogleApiClient.connect() ;
} }
private void resolveNode() {
Wearable.NodeApi.getConnectedNodes(mGoogleApiClient).setResultCallback(new ResultCallback<NodeApi.GetConnectedNodesResult>() {
#Override
public void onResult(NodeApi.GetConnectedNodesResult nodes) {
for (Node node : nodes.getNodes()) {
mNode = node ; } }
}) ; }
public void onConnected(Bundle bundle) {
resolveNode();
}
public void onConnectionSuspended(int i) {
//Improve your code
}
public void onConnectionFailed(ConnectionResult connectionResult) {
//Improve your code
}
Can someone help me out with this to problems please I can't find any way to pass those two problems. I want something like this app: https://play.google.com/store/apps/details?id=com.jumpbyte.flashlight
I'm somewhat of a noob myself but I'm having a similar problem so I'll try to give some input on what I've learned so far.
I don't think any of that code needs to be in onCreate(), since it'll only run once when the app is first opened.
First, I would take all the code you wrote inside of onCreate() and write a seperate method outside of onCreate(). The constants like intent,valor, and value should just be private and inside of the normal Main Activity.
After making a new method and some copy pasta I would run it inside of onMessageReceived().
Here is link to a MessageAPIDemo. Very helpful.
I'm personally having trouble getting my phone to receive a message when the app isn't opened on the phone, somewhat similar to your locked phone problem. I hope I've been of some help.

Categories

Resources