فایل مورد نظر یافت نشد!
Printable View
ساخت یک دایرکتوری (پوشه) در مسیر ایجاد شده برنامه :
String dirPath = getFilesDir().getAbsolutePath() + File.separator + "newfoldername";
File projDir = new File(dirPath);
if (!projDir.exists())
projDir.mkdirs();
این کد اینترنت رو چک نمیکنه. فقط ارتباط با شبکه مثل وای فایل و 3g اینا رو چک میکنه یعنی ابزارهای موجود برای ارتباط با اینترنت. از این کد استفاده کنید
/**
* Return True if host name address is reachable in <b>timeoutMill</b> mili seceond else False
*/
public static boolean isInternetAvailable(int timeoutMill) {
try {
if (InetAddress.getByName((String) UC.getHostName()).isReachable(timeoutMill)) {
return true;
}
return false;
}
catch (Exception e) {
return false;
}
}
این کد راحت تر هستش به نظرم
public static boolean checkPhoneIsRooted() {
try {
Process process = Runtime.getRuntime().exec("su");
DataOutputStream os = new DataOutputStream(
process.getOutputStream());
os.writeBytes("exit");
os.flush();
process.waitFor();
int i = process.exitValue();
if (i == 0)
return true;
else
return false;
}
catch (Exception e) {}
return false;
}
این کد آدرس آی پی تونو برمیگردونه
public String getLocalIPAddress() throws SocketException {
Enumeration<NetworkInterface> nics = NetworkInterface
.getNetworkInterfaces();
while (nics.hasMoreElements()) {
NetworkInterface intf = nics.nextElement();
Enumeration<InetAddress> addrs = intf.getInetAddresses();
while (addrs.hasMoreElements()) {
InetAddress addr = addrs.nextElement();
if ( !addr.isLoopbackAddress()) {
return (addr.getHostAddress().toString());
}
}
}
return (null);
}
این کد چک میکنه SD کارت گوشی mount شده یا نه. ازش برای چک کردن وجود SD کارت هم میشه استفاده کرد
public static boolean checkMountedSDCard() {
if ( !Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED))
return false;
return true;
}
این کد متنی رو برای ارسال sms آماده میکنه. متن رو به برنامه پیامک میفرسته که میتونید بدون کپی کردن متن ازش استفاده کنید
public void sendTextAsSMS(String message) {
Intent smsIntent = new Intent(Intent.ACTION_VIEW);
smsIntent.putExtra("sms_body", message);
smsIntent.setType("vnd.android-dir/mms-sms");
startActivity(smsIntent);
}
این برنامه یه شورتکات از برنامتون تو دسکتاپ میندازه
public static void addAppicationIconOnDesktop(Context context) {
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(context);
if ( !prefs.getBoolean("firstTime", false)) {
Intent HomeScreenShortCut = new Intent(context, ActivityMain.class);
HomeScreenShortCut.setAction(Intent.ACTION_MAIN);
HomeScreenShortCut.putExtra("duplicate", false);
// shortcutIntent is added with addIntent
Intent addIntent = new Intent();
addIntent
.putExtra(Intent.EXTRA_SHORTCUT_INTENT, HomeScreenShortCut);
addIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME,
getStr(R.string.app_name));
addIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESO URCE,
Intent.ShortcutIconResource.fromContext(context,
R.drawable.tsms_icon));
addIntent.setAction("com.android.launcher.action.I NSTALL_SHORTCUT");
context.sendBroadcast(addIntent);
Toast.makeText(context, R.string.added_icon_to_desktop,
Toast.LENGTH_LONG).show();
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("firstTime", true);
editor.commit();
}
}
این کد چک میکنه کاری که شما میخوایید انجام بدید و نیاز به سطح دسترسی داره رو چک میکنه. اینکه شما الان دسترسی لازم رو اعمال کردید یا نه؟
public static boolean hasPermissions(Context context, String... permissions) {
for (String p: permissions)
if (context.checkCallingOrSelfPermission(p) == PackageManager.PERMISSION_DENIED)
return false;
return true;
}
این کد فیلد اول و فیلد انتهایی از یه List رو بر میگردونه
public static final class Lists {
private Lists() {}
public static <T> T getFirst(List<T> list) {
return list != null && !list.isEmpty() ? list.get(0) : null;
}
public static <T> T getLast(List<T> list) {
return list != null && !list.isEmpty() ? list.get(list.size() - 1)
: null;
}
}
این کد چک میکنه عددی که وارد شده صحیح وارد شده یا نه. منظور اینه که مقدار ورودی باید عدد باشه نه حروف قاتی شده باهاش
public static boolean isNumeric(String str) {
return str.matches("-?\\d+(\\.\\d+)?"); // match a number with optional
// '-' and decimal.
}
سلام
خدمت تمامی دوستان و اساتید
اگه ممکنه برخی از کدها رو که عمومیت ندارند(استفاده های خاص دارند) بگید که چکار میکنند و به چه دردی میخورند؟
من تازه کارم و خیلی از این کدها رو اصلا نمیدونم واسه چی کاربرد دارند!
ببخشید که بدجایی عنوان کردم ولی حس کردم لازمه!
مرسی بابت لینک
خیلی سایت خوبی معرفی کردی متشکرم واقعا آموزش های عالی بود ممنونم
ممنون خیلی عالی
اجرای یک دیالوگ یا ... فقط برای بار اول بعد از نصب برنامه
public class MyActivity extends Activity {
public static final String PREFS_NAME = "MyPrefsFile";
@Override
protected void onCreate(Bundle state){
super.onCreate(state);
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
boolean dialogShown = settings.getBoolean("dialogShown", false);
if (!dialogShown) {
// AlertDialog code here
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("dialogShown", true);
editor.commit();
}
}
سلام...
این هم کد روشن و خاموش کردن دیتا اینترنت تو API 20 و پایین تر. که state میتونه true یا false باشه.
ConnectivityManager dataManager;
dataManager = (ConnectivityManager)this.context1.getSystemServic e(Context.CONNECTIVITY_SERVICE);
Method dataMtd = null;
try {
dataMtd = ConnectivityManager.class.getDeclaredMethod("setMo bileDataEnabled", boolean.class);
} catch (NoSuchMethodException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
dataMtd.setAccessible(true);
try {
dataMtd.invoke(dataManager, state);
} catch (IllegalArgumentException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IllegalAccessException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (InvocationTargetException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
این ها رو هم به مینفست اضافه کنید.
<uses-permissionandroid:name="android.permission.CHANGE_NETWORK_STATE"/>
انتقال فایل به پوشه assest
private void copyAssets() {
AssetManager assetManager = getAssets();
String[] files = null;
try {
files = assetManager.list("");
} catch (IOException e) {
Log.e("tag", "Failed to get asset file list.", e);
}
for(String filename : files) {
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open(filename);
File outFile = new File(getExternalFilesDir(null), filename);
out = new FileOutputStream(outFile);
copyFile(in, out);
} catch(IOException e) {
Log.e("tag", "Failed to copy asset file: " + filename, e);
}
finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
// NOOP
}
}
if (out != null) {
try {
out.close();
} catch (IOException e) {
// NOOP
}
}
}
}
}
private void copyFile(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int read;
while((read = in.read(buffer)) != -1){
out.write(buffer, 0, read);
}
}
سلام دوست عزیز
توی قسمت ایف اگه دستوری بنویسیم اجرا نمی کنه مثلا من برای افزایش صدا دستور رفتن به یک اکتیویتی دیگر رو گزاشتم اجرا نکرد
می تونین کمکم کنین
ممنون از پستتون.
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
int keyCode = event.getKeyCode();
if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
if (event.getAction() == KeyEvent.ACTION_UP) {
// Dogme Afzayeshe Seda
Intent intt = new Intent(MainActivity.this, Activity2.class);
startActivity(intt);
}
return true;
} else if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
if (event.getAction() == KeyEvent.ACTION_UP) {
//Dogme Kaheshe Seda
}
return true;
}
return super.dispatchKeyEvent(event);
}
به نظر من باید از SharedPreferences استفاده کرد ،تا حتی اگه کاربر از روی صفحه میانبر حذف کرد مزاحمتی ایجاد نکنه برای کاربر.:لبخندساده:
کد راه اندازی مجدد برنامه
کد HTML:Intent mStartActivity = new Intent(context, StartActivity.class);int mPendingIntentId = 123456;
PendingIntent mPendingIntent = PendingIntent.getActivity(context, mPendingIntentId, mStartActivity, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager mgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, mPendingIntent); System.exit(0);
Intent mStartActivity =newIntent(context,StartActivity.class);
int mPendingIntentId =123456;
PendingIntent mPendingIntent =PendingIntent.getActivity(context, mPendingIntentId, mStartActivity,PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager mgr =(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
mgr.set(AlarmManager.RTC,System.currentTimeMillis()+100, mPendingIntent);
System.exit(0);
بجای StartActivity ، اکتیویتی شروع برنامه رو قرار بدید. .
فقط نمیدونم چرا درست نمایش نمیده . به صورت کد HTML میشه
سلام دوستان
پیدا کردن فاصله با استفاده از Long, Lat بین دو Point
public static float Fasele( final double Lat_b, final double Long_b,final Context ctx ) {
double Lat_a = Point(ctx)[0];
double Long_a = Point(ctx)[1];
double earthRadius = 3958.75;
double latDiff = Math.toRadians(Lat_b-Lat_a);
double lngDiff = Math.toRadians(Long_b-Long_a);
double a = Math.sin(latDiff /2) * Math.sin(latDiff /2) +
Math.cos(Math.toRadians(Lat_a)) * Math.cos(Math.toRadians(Lat_b)) *
Math.sin(lngDiff /2) * Math.sin(lngDiff /2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
double distance = earthRadius * c;
int meterConversion = 1609;
return new Float(distance * meterConversion).floatValue();
}
درج متغیر بین متن :
مثال : چه خبره؟ توی نسخه X
توسط این کد میتونیم مقدار X رو تغییر بدیم
--
اول از همه توی فایل strings در مسیر res/values یه متغیر ایجاد کنید
<string name="versiontitle">توی نسخه %1$s چه خبره؟</string>
هرکجا که نیاز بود متغییر توسط کدنویسی تغییر کنه باید از این نشانه استفاده کنید %1$s
حالا توی کد نویسی جاوا هم:
//version=1
String version;
String news = String.format(getResources().getString(R.string.ve rsiontitle),version);
نتیجه : چه خبره؟ توی نسخه 1
کلاس کار با تاریخ
import java.util.Calendar;import java.util.GregorianCalendar;
public class PersianDate {
private int irYear; // Year part of a Iranian date
private int irMonth; // Month part of a Iranian date
private int irDay; // Day part of a Iranian date
private int gYear; // Year part of a Gregorian date
private int gMonth; // Month part of a Gregorian date
private int gDay; // Day part of a Gregorian date
private int juYear; // Year part of a Julian date
private int juMonth; // Month part of a Julian date
private int juDay; // Day part of a Julian date
private int leap; // Number of years since the last leap year (0 to 4)
private int JDN; // Julian Day Number
private int march; // The march day of Farvardin the first (First day of jaYear)
public PersianDate(){
Calendar calendar = new GregorianCalendar();
setGregorianDate(calendar.get(Calendar.YEAR),
calendar.get(Calendar.MONTH)+1,
calendar.get(Calendar.DAY_OF_MONTH));
}
public PersianDate(int year, int month, int day){
setGregorianDate(year,month,day);
}
public int getIranianYear() {
return irYear;
}
public int getIranianMonth() {
return irMonth;
}
public int getIranianDay() {
return irDay;
}
public int getGregorianYear() {
return gYear;
}
public int getGregorianMonth() {
return gMonth;
}
public int getGregorianDay() {
return gDay;
}
public int getJulianYear() {
return juYear;
}
public int getJulianMonth() {
return juMonth;
}
public int getJulianDay() {
return juDay;
}
public String getIranianDate(){
String Year,Month,Day;
Year = String.valueOf(irYear).substring(2, 4);
if(irMonth < 10){
Month = "0"+String.valueOf(irMonth);
}else{
Month = String.valueOf(irMonth);
}
if(irDay < 10){
Day = "0"+String.valueOf(irDay);
}else{
Day = String.valueOf(irDay);
}
return (Year+""+Month+""+Day);
}
public String getGregorianDate(){
return (gYear+"/"+gMonth+"/"+gDay);
}
public String getJulianDate(){
return (juYear+"/"+juMonth+"/"+juDay);
}
public String getWeekDayStr(){
String weekDayStr[]={
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday",
"Sunday"};
return (weekDayStr[getDayOfWeek()]);
}
public String toString(){
return (getWeekDayStr()+", Gregorian:["+getGregorianDate()+"], Julian:["+getJulianDate()+"], Iranian:["+getIranianDate()+"]");
}
public int getDayOfWeek(){
return (JDN % 7);
}
public void nextDay(){
JDN++;
JDNToIranian();
JDNToJulian();
JDNToGregorian();
}
public void nextDay(int days){
JDN+=days;
JDNToIranian();
JDNToJulian();
JDNToGregorian();
}
public void previousDay(){
JDN--;
JDNToIranian();
JDNToJulian();
JDNToGregorian();
}
public void previousDay(int days){
JDN-=days;
JDNToIranian();
JDNToJulian();
JDNToGregorian();
}
public void setIranianDate(int year, int month, int day){
irYear =year;
irMonth = month;
irDay = day;
JDN = IranianDateToJDN();
JDNToIranian();
JDNToJulian();
JDNToGregorian();
}
public void setGregorianDate(int year, int month, int day){
gYear = year;
gMonth = month;
gDay = day;
JDN = gregorianDateToJDN(year,month,day);
JDNToIranian();
JDNToJulian();
JDNToGregorian();
}
public void setJulianDate(int year, int month, int day){
juYear = year;
juMonth = month;
juDay = day;
JDN = julianDateToJDN(year,month,day);
JDNToIranian();
JDNToJulian();
JDNToGregorian();
}
private void IranianCalendar(){
// Iranian years starting the 33-year rule
int Breaks[]={-61, 9, 38, 199, 426, 686, 756, 818,1111,1181,1210,1635,2060,2097,2192,2262,2324,2 394,2456,3178} ;
int jm,N,leapJ,leapG,jp,j,jump;
gYear = irYear + 621;
leapJ = -14;
jp = Breaks[0];
// Find the limiting years for the Iranian year 'irYear'
j=1;
do{
jm=Breaks[j];
jump = jm-jp;
if (irYear >= jm){
leapJ += (jump / 33 * 8 + (jump % 33) / 4);
jp = jm;
}
j++;
} while ((j<20) && (irYear >= jm));
N = irYear - jp;
// Find the number of leap years from AD 621 to the begining of the current
// Iranian year in the Iranian (Jalali) calendar
leapJ += (N/33 * 8 + ((N % 33) +3)/4);
if ( ((jump % 33) == 4 ) && ((jump-N)==4))
leapJ++;
// And the same in the Gregorian date of Farvardin the first
leapG = gYear/4 - ((gYear /100 + 1) * 3 / 4) - 150;
march = 20 + leapJ - leapG;
// Find how many years have passed since the last leap year
if ( (jump - N) < 6 )
N = N - jump + ((jump + 4)/33 * 33);
leap = (((N+1) % 33)-1) % 4;
if (leap == -1)
leap = 4;
}
public boolean IsLeap(int irYear1){
// Iranian years starting the 33-year rule
int Breaks[]=
{-61, 9, 38, 199, 426, 686, 756, 818,1111,1181,
1210,1635,2060,2097,2192,2262,2324,2394,2456,3178} ;
int jm,N,leapJ,leapG,jp,j,jump;
gYear = irYear1 + 621;
leapJ = -14;
jp = Breaks[0];
// Find the limiting years for the Iranian year 'irYear'
j=1;
do{
jm=Breaks[j];
jump = jm-jp;
if (irYear1 >= jm){
leapJ += (jump / 33 * 8 + (jump % 33) / 4);
jp = jm;
}
j++;
} while ((j<20) && (irYear1 >= jm));
N = irYear1 - jp;
// Find the number of leap years from AD 621 to the begining of the current
// Iranian year in the Iranian (Jalali) calendar
leapJ += (N/33 * 8 + ((N % 33) +3)/4);
if ( ((jump % 33) == 4 ) && ((jump-N)==4))
leapJ++;
// And the same in the Gregorian date of Farvardin the first
leapG = gYear/4 - ((gYear /100 + 1) * 3 / 4) - 150;
march = 20 + leapJ - leapG;
// Find how many years have passed since the last leap year
if ( (jump - N) < 6 )
N = N - jump + ((jump + 4)/33 * 33);
leap = (((N+1) % 33)-1) % 4;
if (leap == -1)
leap = 4;
if (leap==4 || leap==0)
return true;
else
return false;
}
public int IranianDateToJDN(){
IranianCalendar();
return (gregorianDateToJDN(gYear,3,march)+ (irMonth-1) * 31 - irMonth/7 * (irMonth-7) + irDay -1);
}
private void JDNToIranian(){
JDNToGregorian();
irYear = gYear - 621;
IranianCalendar(); // This invocation will update 'leap' and 'march'
int JDN1F = gregorianDateToJDN(gYear,3,march);
int k = JDN - JDN1F;
if (k >= 0){
if (k <= 185){
irMonth = 1 + k/31;
irDay = (k % 31) + 1;
return;
}else
k -= 186;
}else{
irYear--;
k += 179;
if (leap == 1)
k++;
}
irMonth = 7 + k/30;
irDay = (k % 30) + 1;
}
private int julianDateToJDN(int year, int month, int day){
return (year + (month - 8) / 6 + 100100) * 1461/4 + (153 * ((month+9) % 12) + 2)/5 + day - 34840408;
}
private void JDNToJulian(){
int j= 4 * JDN + 139361631;
int i= ((j % 1461)/4) * 5 + 308;
juDay = (i % 153) / 5 + 1;
juMonth = ((i/153) % 12) + 1;
juYear = j/1461 - 100100 + (8-juMonth)/6;
}
private int gregorianDateToJDN(int year, int month, int day){
int jdn = (year + (month - 8) / 6 + 100100) * 1461/4 + (153 * ((month+9) % 12) + 2)/5 + day - 34840408;
jdn = jdn - (year + 100100+(month-8)/6)/100*3/4+752;
return (jdn);
}
private void JDNToGregorian(){
int j= 4 * JDN + 139361631;
j = j + (((((4* JDN +183187720)/146097)*3)/4)*4-3908);
int i= ((j % 1461)/4) * 5 + 308;
gDay = (i % 153) / 5 + 1;
gMonth = ((i/153) % 12) + 1;
gYear = j/1461 - 100100 + (8-gMonth)/6;
}
}
این هم کد تبدیل یک متغیر از نوع Drawable به Bitmap :
public static Bitmap drawableToBitmap(Drawable drawable) {
Bitmap bitmap = null;
if (drawable instanceof BitmapDrawable) {
BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
if (bitmapDrawable.getBitmap() != null) {
return bitmapDrawable.getBitmap();
}
}
if (drawable.getIntrinsicWidth() <= 0 || drawable.getIntrinsicHeight() <= 0) {
bitmap = Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888); // Single color bitmap will be created of 1x1 pixel
} else {
bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
}
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
drawable.draw(canvas);
return bitmap;
}
مهمترین مورد استفاده ی این کد در زمانی است که بخواهید یک drawable را در یک appwidget یا یک notification نشان بدهید.(چون در آن صورت فقط می تونید از imageview استفاده کنید که اون هم فقط bitmap رو قبول می کنه.:لبخند:)
سلام این کد با تغییر زون مشکل پیدا نمی کنه
یعنی زون به زون مثلا زون ۳۸ تا ۴۰ رو هم میتونه صحیح محاسبه کنه؟
من از توابع مثلثاتی و فیثاغورث استفاده میکنم اما تو زون ها و به دلیل کروی بودن زمین در فواصل بیش از ۱۰۰ کیلومتر و زون به زون به مشکل خوردم
اگر کسی اطلاعاتی در این زمینه داره لطفا دریغ نکنه
زاویه رو هم میدونی چجوری میشه محاسبه کرد
البته در فاصله های بیش از ۱۰۰ کیلومتر و یا در زون های هم جوار
یعنی مثلا نقطه الف در زون ۳۸ هستش و نقطه ب در زون ۳۹